Lokasjon-input: del posisjon i chat med kartvisning (oppgave 29.9)

Ny «Del posisjon»-knapp i ChatInput ved siden av tale/video-knappene.
Bruker Geolocation API for å hente brukerens posisjon, oppretter en
content-node med metadata.location { lat, lon, address }.

Reverse geocoding via Nominatim (best-effort) gir adresse i metadata.
Kartvisning i chat via Leaflet/OpenStreetMap viser posisjonen inline.

Komponenter:
- LocationShare.svelte: knapp + geolocation + geocoding + node-opprettelse
- LocationMap.svelte: Leaflet-kart med markør og adresse-popup
- Leaflet lastes via CDN (unpkg) i app.html
This commit is contained in:
vegard 2026-03-18 22:36:08 +00:00
parent 87170e8059
commit 6729a35435
6 changed files with 219 additions and 4 deletions

View file

@ -7,6 +7,8 @@
<link rel="manifest" href="/manifest.json" />
<link rel="icon" type="image/svg+xml" href="/icon.svg" />
<link rel="apple-touch-icon" href="/icon.svg" />
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin="" />
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">

View file

@ -1,6 +1,7 @@
<script lang="ts">
import VoiceRecorder from './VoiceRecorder.svelte';
import VideoRecorder from './VideoRecorder.svelte';
import LocationShare from './LocationShare.svelte';
import { uploadMedia, casUrl } from '$lib/api';
interface Props {
@ -143,6 +144,12 @@
disabled={disabled || submitting}
onerror={(msg) => { error = msg; }}
/>
<LocationShare
{accessToken}
contextId={contextId}
disabled={disabled || submitting}
onerror={(msg) => { error = msg; }}
/>
<button
onclick={handleSubmit}
disabled={isEmpty || submitting || disabled}

View file

@ -0,0 +1,57 @@
<script lang="ts">
import { onMount } from 'svelte';
import { browser } from '$app/environment';
interface Props {
lat: number;
lon: number;
address?: string;
/** Map height in pixels */
height?: number;
}
let { lat, lon, address, height = 200 }: Props = $props();
let mapContainer: HTMLDivElement | undefined = $state();
let map: L.Map | undefined;
onMount(() => {
if (!browser || !mapContainer) return;
const L = (window as any).L;
if (!L) return;
map = L.map(mapContainer, {
scrollWheelZoom: false,
dragging: true,
zoomControl: true,
}).setView([lat, lon], 15);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
maxZoom: 19,
}).addTo(map);
const marker = L.marker([lat, lon]).addTo(map);
if (address) {
marker.bindPopup(address);
}
return () => {
map?.remove();
map = undefined;
};
});
</script>
<div class="overflow-hidden rounded-lg">
<div
bind:this={mapContainer}
style="height: {height}px; width: 100%; min-width: 200px;"
></div>
{#if address}
<p class="mt-1 text-xs text-gray-500 truncate" title={address}>{address}</p>
{:else}
<p class="mt-1 text-xs text-gray-400">{lat}, {lon}</p>
{/if}
</div>

View file

@ -0,0 +1,117 @@
<script lang="ts">
import { createNode } from '$lib/api';
interface Props {
accessToken?: string;
/** Context node (e.g. communication node) for belongs_to edge */
contextId?: string;
disabled?: boolean;
onerror?: (message: string) => void;
}
let { accessToken, contextId, disabled = false, onerror }: Props = $props();
type LocationState = 'idle' | 'requesting' | 'geocoding' | 'saving';
let locState: LocationState = $state('idle');
async function shareLocation() {
if (!accessToken) {
onerror?.('Ikke innlogget — kan ikke dele posisjon');
return;
}
if (!navigator.geolocation) {
onerror?.('Geolokalisering støttes ikke i denne nettleseren');
return;
}
locState = 'requesting';
try {
const position = await new Promise<GeolocationPosition>((resolve, reject) => {
navigator.geolocation.getCurrentPosition(resolve, reject, {
enableHighAccuracy: true,
timeout: 15000,
maximumAge: 60000,
});
});
const lat = Math.round(position.coords.latitude * 1e6) / 1e6;
const lon = Math.round(position.coords.longitude * 1e6) / 1e6;
// Try reverse geocoding via Nominatim (best-effort)
let address: string | undefined;
locState = 'geocoding';
try {
const res = await fetch(
`https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lon}&format=json&zoom=16&addressdetails=0`,
{ headers: { 'User-Agent': 'Synops/1.0' } }
);
if (res.ok) {
const data = await res.json();
address = data.display_name;
}
} catch {
// Geocoding is optional — continue without address
}
locState = 'saving';
const title = address
? `Posisjon: ${address}`
: `Posisjon: ${lat}, ${lon}`;
await createNode(accessToken, {
node_kind: 'content',
title,
content: address || `${lat}, ${lon}`,
visibility: 'hidden',
context_id: contextId,
metadata: {
source: 'geolocation',
location: { lat, lon, ...(address ? { address } : {}) },
},
});
} catch (e) {
if (e instanceof GeolocationPositionError) {
const msgs: Record<number, string> = {
1: 'Posisjonstilgang avslått. Sjekk nettleserinnstillinger.',
2: 'Kunne ikke hente posisjon. Prøv igjen.',
3: 'Tidsavbrudd ved posisjonshenting. Prøv igjen.',
};
onerror?.(msgs[e.code] || 'Ukjent posisjonsfeil');
} else {
onerror?.(e instanceof Error ? e.message : 'Feil ved deling av posisjon');
}
} finally {
locState = 'idle';
}
}
</script>
{#if locState === 'idle'}
<button
onclick={shareLocation}
disabled={disabled || !accessToken}
class="flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-gray-400 transition-colors hover:bg-green-50 hover:text-green-500 disabled:cursor-not-allowed disabled:opacity-40"
aria-label="Del posisjon"
title="Del posisjon"
>
<!-- Map pin icon -->
<svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
<path stroke-linecap="round" stroke-linejoin="round" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
</button>
{:else}
<div class="flex items-center gap-1.5">
<svg class="h-4 w-4 animate-spin text-green-600" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
</svg>
<span class="text-xs text-green-600">
{#if locState === 'requesting'}Henter posisjon…{:else if locState === 'geocoding'}Finner adresse…{:else}Lagrer…{/if}
</span>
</div>
{/if}

View file

@ -5,6 +5,7 @@
import { createNode, casUrl } from '$lib/api';
import ChatInput from '$lib/components/ChatInput.svelte';
import AudioPlayer from '$lib/components/AudioPlayer.svelte';
import LocationMap from '$lib/components/LocationMap.svelte';
import { tick } from 'svelte';
const session = $derived($page.data.session as Record<string, unknown> | undefined);
@ -203,6 +204,25 @@
return (meta.transcription?.segment_count ?? 0) > 0;
} catch { return false; }
}
/** Check if this node is a location node */
function isLocationNode(node: Node): boolean {
try {
const meta = JSON.parse(node.metadata ?? '{}');
return meta.location && typeof meta.location.lat === 'number' && typeof meta.location.lon === 'number';
} catch { return false; }
}
/** Get location data from a node */
function getLocation(node: Node): { lat: number; lon: number; address?: string } | undefined {
try {
const meta = JSON.parse(node.metadata ?? '{}');
if (meta.location?.lat != null && meta.location?.lon != null) {
return meta.location;
}
} catch {}
return undefined;
}
</script>
<div class="flex h-screen flex-col bg-gray-50">
@ -260,9 +280,10 @@
{@const own = isOwnMessage(msg)}
{@const audio = isAudioNode(msg)}
{@const image = isImageNode(msg)}
{@const location = isLocationNode(msg)}
{@const bot = isAgentMessage(msg)}
<div class="flex {own ? 'justify-end' : 'justify-start'}">
<div class="max-w-[75%] {own ? (audio || image ? 'bg-blue-50 border border-blue-200 text-gray-900' : 'bg-blue-600 text-white') : bot ? 'bg-amber-50 border border-amber-200 text-gray-900' : 'bg-white border border-gray-200 text-gray-900'} rounded-2xl px-4 py-2 shadow-sm">
<div class="max-w-[75%] {own ? (audio || image || location ? 'bg-blue-50 border border-blue-200 text-gray-900' : 'bg-blue-600 text-white') : bot ? 'bg-amber-50 border border-amber-200 text-gray-900' : 'bg-white border border-gray-200 text-gray-900'} rounded-2xl px-4 py-2 shadow-sm">
{#if !own}
<p class="mb-0.5 text-xs font-medium {bot ? 'text-amber-700' : 'text-blue-600'}">
{#if bot}<span title="AI-agent">🤖 </span>{/if}{senderName(msg)}
@ -296,12 +317,24 @@
<p class="mt-1 text-xs text-gray-500 italic">{imageDescription(msg)}</p>
{/if}
</div>
{:else if location}
{@const loc = getLocation(msg)}
{#if loc}
<div class="flex items-center gap-1.5 mb-1">
<svg class="h-3.5 w-3.5 text-green-500 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
<path stroke-linecap="round" stroke-linejoin="round" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
<span class="text-[11px] font-medium text-green-600">Posisjon</span>
</div>
<LocationMap lat={loc.lat} lon={loc.lon} address={loc.address} height={180} />
{/if}
{:else}
<p class="text-sm whitespace-pre-wrap break-words">
{msg.content || ''}
</p>
{/if}
<p class="mt-1 text-right text-[10px] {own && !audio && !image ? 'text-blue-200' : 'text-gray-400'}">
<p class="mt-1 text-right text-[10px] {own && !audio && !image && !location ? 'text-blue-200' : 'text-gray-400'}">
{formatTime(msg)}
</p>
</div>

View file

@ -406,8 +406,7 @@ noden er det som lever videre.
- [x] 29.8 Video-prosessering: `synops-video` CLI for transcode (H.264), thumbnail-generering, og varighet-uttrekk. Input: `--cas-hash <hash>`. Output: ny CAS-hash (trancodet) + thumbnail CAS-hash.
### Geolokasjon
- [~] 29.9 Lokasjon-input: "Del posisjon"-knapp i input-komponenten → Geolocation API → node med `metadata.location: { "lat": 59.91, "lon": 10.75 }`. Kart-visning i node-detaljer (Leaflet/OpenStreetMap). Valgfritt: reverse geocoding via Nominatim for adresse.
> Påbegynt: 2026-03-18T22:30
- [x] 29.9 Lokasjon-input: "Del posisjon"-knapp i input-komponenten → Geolocation API → node med `metadata.location: { "lat": 59.91, "lon": 10.75 }`. Kart-visning i node-detaljer (Leaflet/OpenStreetMap). Valgfritt: reverse geocoding via Nominatim for adresse.
### Håndskrift/tegning
- [ ] 29.10 Tegne-input: enkel canvas-basert tegneflate i input-komponenten. Eksporter som PNG → CAS → media-node. Ikke whiteboard (det er et eget verktøy) — dette er "rask skisse som input", som en post-it.