worldwide todo list: global map (List/Map toggle, clustered category pins, Global strip, pick on map, location_precision, tasks.geojson)
All checks were successful
Deploy production / deploy (push) Successful in 1m13s
All checks were successful
Deploy production / deploy (push) Successful in 1m13s
This commit is contained in:
@@ -25,6 +25,7 @@ const WORLDTODO_SCALES = ['planet', 'region', 'country', 'city', 'street'] as co
|
||||
const WORLDTODO_STATUSES = ['open', 'in_progress', 'done'] as const;
|
||||
const WORLDTODO_REQUEST_KINDS = ['add', 'edit', 'delete'] as const;
|
||||
const WORLDTODO_REQUEST_STATUSES = ['pending', 'approved', 'rejected'] as const;
|
||||
const WORLDTODO_LOCATION_PRECISIONS = ['exact', 'approximate', 'none'] as const;
|
||||
|
||||
const tsvector = customType<{ data: string }>({ dataType: () => 'tsvector' });
|
||||
|
||||
@@ -36,6 +37,11 @@ export const worldtodoRequestStatus = worldtodoSchema.enum(
|
||||
WORLDTODO_REQUEST_STATUSES
|
||||
);
|
||||
|
||||
export const worldtodoLocationPrecision = worldtodoSchema.enum(
|
||||
'location_precision',
|
||||
WORLDTODO_LOCATION_PRECISIONS
|
||||
);
|
||||
|
||||
export const worldtodoCategories = worldtodoSchema.table('categories', {
|
||||
slug: text('slug').primaryKey(),
|
||||
label: text('label').notNull(),
|
||||
@@ -61,6 +67,13 @@ export const worldtodoTasks = worldtodoSchema.table(
|
||||
countryCode: text('country_code'),
|
||||
lat: doublePrecision('lat'),
|
||||
lon: doublePrecision('lon'),
|
||||
/**
|
||||
* How the map treats lat/lon: street and city tasks are exact pins, region and country
|
||||
* pins sit at a rough centre, planet tasks (or no coordinates) get no pin. Set from scale
|
||||
* and lat/lon by the tasks_location_precision trigger (hand-written in the migration), so
|
||||
* it never drifts from the data.
|
||||
*/
|
||||
locationPrecision: worldtodoLocationPrecision('location_precision'),
|
||||
status: worldtodoStatus('status').notNull().default('open'),
|
||||
sourceUrls: text('source_urls').array().notNull(),
|
||||
/** Date of the main source as given ('2026-09', '2026-10-21'). */
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
EDITABLE_FIELDS,
|
||||
RESERVED_SLUGS,
|
||||
changedFields,
|
||||
precisionFor,
|
||||
type Category,
|
||||
type PublicTask,
|
||||
type RequestKind,
|
||||
@@ -18,7 +19,8 @@ import {
|
||||
|
||||
const TASK_COLUMNS = sql`
|
||||
t.id, t.slug, t.title, t.description, t.scale::text as scale, t.category,
|
||||
t.location_name, t.country_code, t.lat, t.lon, t.status::text as status, t.source_urls,
|
||||
t.location_name, t.country_code, t.lat, t.lon, t.location_precision::text as location_precision,
|
||||
t.status::text as status, t.source_urls,
|
||||
t.source_date, t.confidence, t.verification_note, t.as_of::text as as_of,
|
||||
t.created_at, t.updated_at, t.deleted_at`;
|
||||
|
||||
@@ -38,17 +40,23 @@ function toDate(v: unknown): Date | null {
|
||||
const iso = (v: unknown) => toDate(v)?.toISOString() ?? '';
|
||||
|
||||
export function toTask(r: Row): PublicTask {
|
||||
const lat = r.lat === null || r.lat === undefined ? null : Number(r.lat);
|
||||
const lon = r.lon === null || r.lon === undefined ? null : Number(r.lon);
|
||||
const scale = r.scale as PublicTask['scale'];
|
||||
return {
|
||||
id: Number(r.id),
|
||||
slug: String(r.slug),
|
||||
title: String(r.title),
|
||||
description: String(r.description),
|
||||
scale: r.scale as PublicTask['scale'],
|
||||
scale,
|
||||
category: String(r.category),
|
||||
locationName: String(r.location_name),
|
||||
countryCode: (r.country_code as string | null) ?? null,
|
||||
lat: r.lat === null || r.lat === undefined ? null : Number(r.lat),
|
||||
lon: r.lon === null || r.lon === undefined ? null : Number(r.lon),
|
||||
lat,
|
||||
lon,
|
||||
locationPrecision:
|
||||
(r.location_precision as PublicTask['locationPrecision'] | null) ??
|
||||
precisionFor(scale, lat, lon),
|
||||
status: r.status as PublicTask['status'],
|
||||
sourceUrls: (r.source_urls as string[]) ?? [],
|
||||
sourceDate: (r.source_date as string | null) ?? null,
|
||||
|
||||
155
src/lib/worldtodo/MapPicker.svelte
Normal file
155
src/lib/worldtodo/MapPicker.svelte
Normal file
@@ -0,0 +1,155 @@
|
||||
<script lang="ts">
|
||||
import 'leaflet/dist/leaflet.css';
|
||||
import type * as Leaflet from 'leaflet';
|
||||
import { untrack } from 'svelte';
|
||||
import { addThemedTiles, loadLeaflet } from './tiles';
|
||||
import MapPin from 'lucide-svelte/icons/map-pin';
|
||||
|
||||
// Optional "Pick on map" for the request form: a click fills the latitude/longitude inputs
|
||||
// (5 decimals, about a metre). The coordinates travel in the change request, so the owner
|
||||
// sees them in the queue before anything is applied.
|
||||
let { lat = $bindable(''), lon = $bindable('') }: { lat?: string; lon?: string } = $props();
|
||||
|
||||
let open = $state(false);
|
||||
let el = $state<HTMLDivElement>();
|
||||
let L: typeof Leaflet | null = null;
|
||||
let map: Leaflet.Map | null = null;
|
||||
let marker: Leaflet.CircleMarker | null = null;
|
||||
|
||||
const parsed = () => {
|
||||
const a = Number(lat);
|
||||
const b = Number(lon);
|
||||
return lat !== '' && lon !== '' && Math.abs(a) <= 90 && Math.abs(b) <= 180
|
||||
? ([a, b] as [number, number])
|
||||
: null;
|
||||
};
|
||||
|
||||
function place(at: [number, number] | null) {
|
||||
if (!map || !L) return;
|
||||
if (!at) {
|
||||
marker?.remove();
|
||||
marker = null;
|
||||
return;
|
||||
}
|
||||
if (marker) marker.setLatLng(at);
|
||||
else
|
||||
marker = L.circleMarker(at, {
|
||||
radius: 8,
|
||||
color: '#fff',
|
||||
weight: 2,
|
||||
fillColor: '#ea580c',
|
||||
fillOpacity: 1
|
||||
}).addTo(map);
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if (!open || !el) return;
|
||||
const node = el;
|
||||
let disposed = false;
|
||||
let stopTiles = () => {};
|
||||
loadLeaflet().then((Lf) => {
|
||||
if (disposed) return;
|
||||
L = Lf;
|
||||
const start = untrack(parsed);
|
||||
const m = Lf.map(node, { scrollWheelZoom: false, worldCopyJump: true, minZoom: 1 });
|
||||
map = m;
|
||||
stopTiles = addThemedTiles(Lf, m);
|
||||
if (start) m.setView(start, 12);
|
||||
else m.setView([30, 10], 1);
|
||||
m.on('focus', () => m.scrollWheelZoom.enable());
|
||||
m.on('blur', () => m.scrollWheelZoom.disable());
|
||||
m.on('click', (e: Leaflet.LeafletMouseEvent) => {
|
||||
m.scrollWheelZoom.enable();
|
||||
const w = e.latlng.wrap();
|
||||
lat = w.lat.toFixed(5);
|
||||
lon = w.lng.toFixed(5);
|
||||
});
|
||||
untrack(() => place(start));
|
||||
});
|
||||
return () => {
|
||||
disposed = true;
|
||||
stopTiles();
|
||||
map?.remove();
|
||||
map = null;
|
||||
marker = null;
|
||||
};
|
||||
});
|
||||
// Typed coordinates move the marker too.
|
||||
$effect(() => {
|
||||
void lat;
|
||||
void lon;
|
||||
untrack(() => place(parsed()));
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="picker">
|
||||
<button type="button" class="toggle" aria-expanded={open} onclick={() => (open = !open)}>
|
||||
<MapPin size={14} aria-hidden="true" />{open ? 'Hide map' : 'Pick on map'}
|
||||
</button>
|
||||
{#if lat || lon}
|
||||
<button
|
||||
type="button"
|
||||
class="toggle"
|
||||
onclick={() => {
|
||||
lat = '';
|
||||
lon = '';
|
||||
}}>Clear position</button
|
||||
>
|
||||
{/if}
|
||||
{#if open}
|
||||
<div class="mini" bind:this={el} aria-label="Click the map to set the position"></div>
|
||||
<p class="help">
|
||||
Click where the problem is; zoom in for a street. This fills the fields above.
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
/* Keyless fallback (OSM tiles) darkened to sit in the dark theme. */
|
||||
:global(.wt-tiles-dim) {
|
||||
filter: invert(1) hue-rotate(180deg) brightness(0.85) contrast(0.9) saturate(0.6);
|
||||
}
|
||||
.picker {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.4rem;
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
.toggle {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
padding: 0.3rem 0.7rem;
|
||||
border: 1px solid var(--site-border);
|
||||
border-radius: 999px;
|
||||
background: transparent;
|
||||
color: var(--site-text);
|
||||
font-size: 0.78rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
.toggle:hover,
|
||||
.toggle:focus-visible {
|
||||
border-color: var(--site-text);
|
||||
}
|
||||
.mini {
|
||||
flex-basis: 100%;
|
||||
height: 260px;
|
||||
border: 1px solid var(--site-border);
|
||||
border-radius: 0.7rem;
|
||||
overflow: hidden;
|
||||
background: #0e0e0e;
|
||||
cursor: crosshair;
|
||||
z-index: 0;
|
||||
}
|
||||
.mini :global(.leaflet-container) {
|
||||
cursor: crosshair;
|
||||
}
|
||||
.mini :global(.leaflet-control-attribution) {
|
||||
font-size: 0.6rem;
|
||||
}
|
||||
.help {
|
||||
flex-basis: 100%;
|
||||
font-size: 0.72rem;
|
||||
color: var(--site-muted);
|
||||
}
|
||||
</style>
|
||||
@@ -1,6 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { untrack } from 'svelte';
|
||||
import IconTile from './IconTile.svelte';
|
||||
import MapPicker from './MapPicker.svelte';
|
||||
import { SCALE_ICONS } from './icons';
|
||||
import {
|
||||
SCALE_INFO,
|
||||
@@ -212,6 +213,7 @@
|
||||
{#if err('lon')}<span class="err" id="{id}-lon-err">{err('lon')}</span>{/if}
|
||||
</div>
|
||||
</div>
|
||||
<MapPicker bind:lat bind:lon />
|
||||
</details>
|
||||
|
||||
<fieldset class="field" aria-describedby={described('source_urls', true)}>
|
||||
|
||||
760
src/lib/worldtodo/WorldMap.svelte
Normal file
760
src/lib/worldtodo/WorldMap.svelte
Normal file
@@ -0,0 +1,760 @@
|
||||
<script lang="ts">
|
||||
import 'leaflet/dist/leaflet.css';
|
||||
import type * as Leaflet from 'leaflet';
|
||||
import { mount, unmount, untrack, type Component } from 'svelte';
|
||||
import { categoryIcon } from './icons';
|
||||
import { clusterPoints, coordKey, ringOffsets } from './cluster';
|
||||
import { addThemedTiles, loadLeaflet } from './tiles';
|
||||
import {
|
||||
SCALE_INFO,
|
||||
STATUS_LABELS,
|
||||
WORLDTODO_SCALES,
|
||||
type Category,
|
||||
type PublicTask,
|
||||
type Scale
|
||||
} from './shared';
|
||||
|
||||
// The task map (List / Map toggle, tracker #4641): one pin per task with coordinates,
|
||||
// coloured by category and sized by scale; clusters with counts when zoomed out; tasks on
|
||||
// the same centroid fan out in a ring from zoom 6. Planet tasks never get a pin (the page
|
||||
// shows them in the Global strip). Pins are focusable buttons; the list stays the full
|
||||
// alternative to the map.
|
||||
let {
|
||||
tasks,
|
||||
categories,
|
||||
highlight = null,
|
||||
fitKey = ''
|
||||
}: {
|
||||
tasks: PublicTask[];
|
||||
categories: Category[];
|
||||
/** Slug whose pin (or cluster) is emphasised, e.g. while hovering its list card. */
|
||||
highlight?: string | null;
|
||||
/** Refit the view when this changes (filters), not on live updates. */
|
||||
fitKey?: string;
|
||||
} = $props();
|
||||
|
||||
const BASE = '/projects/worldwide-todo';
|
||||
const PIN: Record<Scale, number> = { street: 16, city: 20, country: 26, region: 32, planet: 36 };
|
||||
const FOCUS_ZOOM: Record<Scale, number> = {
|
||||
street: 16,
|
||||
city: 12,
|
||||
country: 6,
|
||||
region: 5,
|
||||
planet: 3
|
||||
};
|
||||
const SPREAD_FROM = 6;
|
||||
const UNCLUSTER_FROM = 10;
|
||||
|
||||
let el: HTMLDivElement;
|
||||
let L: typeof Leaflet | null = null;
|
||||
let map: Leaflet.Map | null = null;
|
||||
let layer: Leaflet.LayerGroup | null = null;
|
||||
let ready = $state(false);
|
||||
let failed = $state(false);
|
||||
let scrollOn = $state(false);
|
||||
// eslint-disable-next-line svelte/prefer-svelte-reactivity -- plain lookup/scratch, never read reactively
|
||||
const pins = new Map<string, Leaflet.Marker>();
|
||||
/** slug → the element showing it (its own pin or the cluster that holds it). */
|
||||
// eslint-disable-next-line svelte/prefer-svelte-reactivity -- plain lookup/scratch, never read reactively
|
||||
const shownBy = new Map<string, HTMLElement>();
|
||||
// eslint-disable-next-line svelte/prefer-svelte-reactivity -- plain lookup/scratch, never read reactively
|
||||
const clusterOf = new Map<string, { at: Leaflet.LatLng; members: PublicTask[] }>();
|
||||
|
||||
const located = $derived(
|
||||
tasks.filter((t) => t.locationPrecision !== 'none' && t.lat !== null && t.lon !== null)
|
||||
);
|
||||
const catBySlug = $derived(new Map(categories.map((c) => [c.slug, c])));
|
||||
const usedCats = $derived(categories.filter((c) => located.some((t) => t.category === c.slug)));
|
||||
|
||||
const esc = (s: string) =>
|
||||
s.replace(
|
||||
/[&<>"']/g,
|
||||
(ch) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[ch]!
|
||||
);
|
||||
const colourOf = (t: PublicTask) => {
|
||||
const c = catBySlug.get(t.category)?.colour ?? '';
|
||||
return /^#[0-9a-f]{3,8}$/i.test(c) ? c : '#737373';
|
||||
};
|
||||
const label = (t: PublicTask) =>
|
||||
`${t.title}, ${SCALE_INFO[t.scale].label.toLowerCase()}, ${STATUS_LABELS[t.status].toLowerCase()}`;
|
||||
|
||||
// eslint-disable-next-line svelte/prefer-svelte-reactivity -- plain lookup/scratch, never read reactively
|
||||
const svgCache = new Map<string, string>();
|
||||
function iconSvg(key: string | undefined) {
|
||||
const k = key ?? '';
|
||||
let svg = svgCache.get(k);
|
||||
if (svg === undefined) {
|
||||
const host = document.createElement('div');
|
||||
const c = mount(categoryIcon(key) as unknown as Component<Record<string, unknown>>, {
|
||||
target: host,
|
||||
props: { size: 14, strokeWidth: 2.5, 'aria-hidden': 'true' }
|
||||
});
|
||||
svg = host.innerHTML.replace(/<!--[^>]*-->/g, '');
|
||||
unmount(c);
|
||||
svgCache.set(k, svg);
|
||||
}
|
||||
return svg;
|
||||
}
|
||||
const CHECK =
|
||||
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg>';
|
||||
|
||||
function pinHtml(t: PublicTask) {
|
||||
const inner =
|
||||
t.status === 'done'
|
||||
? CHECK
|
||||
: PIN[t.scale] >= 20
|
||||
? iconSvg(catBySlug.get(t.category)?.icon)
|
||||
: '';
|
||||
return `<span class="wt-pin ${t.status} ${t.locationPrecision}" style="--c:${colourOf(t)};--s:${PIN[t.scale]}px">${inner}</span>`;
|
||||
}
|
||||
|
||||
function popupHtml(t: PublicTask) {
|
||||
const cat = catBySlug.get(t.category);
|
||||
const href = `${BASE}/${encodeURIComponent(t.slug)}`;
|
||||
const change = `${BASE}/request?kind=edit&task=${encodeURIComponent(t.slug)}`;
|
||||
return `<div class="wt-pop">
|
||||
<div class="wt-chips">
|
||||
<span class="wt-chip">${esc(SCALE_INFO[t.scale].label)}</span>
|
||||
<span class="wt-chip"><i style="background:${colourOf(t)}"></i>${esc(cat?.label ?? t.category)}</span>
|
||||
<span class="wt-status ${t.status}">${esc(STATUS_LABELS[t.status])}</span>
|
||||
</div>
|
||||
<a class="wt-title" href="${href}">${esc(t.title)}</a>
|
||||
<p class="wt-where">${esc(t.locationName)}${t.locationPrecision === 'approximate' ? ' · <em>approximate location</em>' : ''}</p>
|
||||
<p class="wt-desc">${esc(t.description)}</p>
|
||||
<div class="wt-actions">
|
||||
<a class="wt-btn primary" href="${href}">View task</a>
|
||||
<a class="wt-btn" href="${change}">Request change</a>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function clusterPopupHtml(members: PublicTask[]) {
|
||||
const items = members
|
||||
.map(
|
||||
(t) =>
|
||||
`<li><i style="background:${colourOf(t)}"></i><a href="${BASE}/${encodeURIComponent(t.slug)}">${esc(t.title)}</a><span class="wt-status ${t.status}">${esc(STATUS_LABELS[t.status])}</span></li>`
|
||||
)
|
||||
.join('');
|
||||
return `<div class="wt-pop"><p class="wt-where">${members.length} tasks here</p><ul class="wt-list">${items}</ul></div>`;
|
||||
}
|
||||
|
||||
const popupOptions = () => ({
|
||||
className: 'wt-popup',
|
||||
maxWidth: Math.min(300, (el?.clientWidth ?? 320) - 48),
|
||||
minWidth: Math.min(220, (el?.clientWidth ?? 320) - 64),
|
||||
autoPanPadding: [16, 16] as [number, number]
|
||||
});
|
||||
|
||||
function render() {
|
||||
if (!map || !L || !layer) return;
|
||||
const Lf = L;
|
||||
const m = map;
|
||||
layer.clearLayers();
|
||||
pins.clear();
|
||||
shownBy.clear();
|
||||
clusterOf.clear();
|
||||
const z = m.getZoom();
|
||||
|
||||
type P = { t: PublicTask; x: number; y: number; weight: number; at: Leaflet.LatLng };
|
||||
const all: P[] = located.map((t) => {
|
||||
const at = Lf.latLng(t.lat!, t.lon!);
|
||||
const p = m.project(at, z);
|
||||
return { t, x: p.x, y: p.y, weight: PIN[t.scale], at };
|
||||
});
|
||||
// From SPREAD_FROM, tasks sharing one coordinate (country centroids) fan out in a ring
|
||||
// and never cluster; from UNCLUSTER_FROM nothing clusters.
|
||||
const fanned: P[][] = [];
|
||||
let rest = all;
|
||||
if (z >= SPREAD_FROM) {
|
||||
// eslint-disable-next-line svelte/prefer-svelte-reactivity -- plain lookup/scratch, never read reactively
|
||||
const byCoord = new Map<string, P[]>();
|
||||
for (const p of all) {
|
||||
const k = coordKey(p.t.lat!, p.t.lon!);
|
||||
byCoord.set(k, [...(byCoord.get(k) ?? []), p]);
|
||||
}
|
||||
for (const g of byCoord.values()) if (g.length > 1) fanned.push(g);
|
||||
rest = all.filter((p) => !fanned.some((g) => g.includes(p)));
|
||||
}
|
||||
const groups: P[][] = [
|
||||
...clusterPoints(rest, z >= UNCLUSTER_FROM ? 0 : z >= SPREAD_FROM ? 36 : 40),
|
||||
...fanned.flatMap((g) => {
|
||||
const ring = ringOffsets(g.length);
|
||||
return g.map((p, i) => [
|
||||
{ ...p, at: m.unproject([p.x + ring[i].dx, p.y + ring[i].dy], z) }
|
||||
]);
|
||||
})
|
||||
];
|
||||
|
||||
for (const g of groups) {
|
||||
if (g.length === 1) {
|
||||
const { t, at } = g[0];
|
||||
const s = PIN[t.scale];
|
||||
const marker = Lf.marker(at, {
|
||||
icon: Lf.divIcon({
|
||||
className: 'wt-pin-wrap',
|
||||
html: pinHtml(t),
|
||||
iconSize: [s, s],
|
||||
iconAnchor: [s / 2, s / 2],
|
||||
popupAnchor: [0, -s / 2]
|
||||
}),
|
||||
keyboard: true,
|
||||
riseOnHover: true,
|
||||
zIndexOffset: s * 10
|
||||
});
|
||||
marker.bindPopup(popupHtml(t), popupOptions());
|
||||
marker.on('add', () => {
|
||||
const e = marker.getElement();
|
||||
if (!e) return;
|
||||
e.setAttribute('role', 'button');
|
||||
e.setAttribute('aria-label', label(t));
|
||||
e.removeAttribute('title');
|
||||
shownBy.set(t.slug, e);
|
||||
if (t.slug === highlight) e.classList.add('wt-hl');
|
||||
});
|
||||
pins.set(t.slug, marker);
|
||||
layer.addLayer(marker);
|
||||
continue;
|
||||
}
|
||||
const members = g.map((p) => p.t);
|
||||
const bounds = Lf.latLngBounds(g.map((p) => p.at));
|
||||
const center = bounds.getCenter();
|
||||
const colours = [...new Set(members.map(colourOf))].slice(0, 8);
|
||||
const step = 100 / colours.length;
|
||||
const ring = colours.map((c, i) => `${c} ${i * step}% ${(i + 1) * step}%`).join(', ');
|
||||
const size = Math.min(52, 30 + members.length * 2);
|
||||
const marker = Lf.marker(center, {
|
||||
icon: Lf.divIcon({
|
||||
className: 'wt-pin-wrap',
|
||||
html: `<span class="wt-cluster" style="--s:${size}px;background:conic-gradient(${ring})"><span>${members.length}</span></span>`,
|
||||
iconSize: [size, size],
|
||||
iconAnchor: [size / 2, size / 2]
|
||||
}),
|
||||
keyboard: true,
|
||||
zIndexOffset: 1000
|
||||
});
|
||||
const entry = { at: center, members };
|
||||
marker.on('click', () => {
|
||||
const sameSpot = bounds.getNorthEast().distanceTo(bounds.getSouthWest()) < 200;
|
||||
if (sameSpot || m.getZoom() >= UNCLUSTER_FROM)
|
||||
Lf.popup(popupOptions())
|
||||
.setLatLng(center)
|
||||
.setContent(clusterPopupHtml(members))
|
||||
.openOn(m);
|
||||
else m.flyToBounds(bounds, { padding: [56, 56], maxZoom: UNCLUSTER_FROM, duration: 0.6 });
|
||||
});
|
||||
marker.on('add', () => {
|
||||
const e = marker.getElement();
|
||||
if (!e) return;
|
||||
e.setAttribute('role', 'button');
|
||||
e.setAttribute('aria-label', `${members.length} tasks here, zoom in`);
|
||||
e.removeAttribute('title');
|
||||
for (const t of members) shownBy.set(t.slug, e);
|
||||
if (highlight && members.some((t) => t.slug === highlight)) e.classList.add('wt-hl');
|
||||
});
|
||||
for (const t of members) clusterOf.set(t.slug, entry);
|
||||
layer.addLayer(marker);
|
||||
}
|
||||
}
|
||||
|
||||
function fit() {
|
||||
if (!map || !L) return;
|
||||
const pts = located.map((t) => [t.lat!, t.lon!] as [number, number]);
|
||||
if (!pts.length) map.setView([25, 10], 2);
|
||||
else if (pts.length === 1) map.setView(pts[0], FOCUS_ZOOM[located[0].scale]);
|
||||
else map.fitBounds(L.latLngBounds(pts), { padding: [36, 36], maxZoom: 12 });
|
||||
}
|
||||
|
||||
/** Fly to a task's pin and open its popup (list card click in map view). */
|
||||
export function focusTask(slug: string) {
|
||||
const t = located.find((x) => x.slug === slug);
|
||||
if (!t || !map) return;
|
||||
const m = map;
|
||||
const r = el.getBoundingClientRect();
|
||||
if (r.top < 0 || r.bottom > window.innerHeight)
|
||||
el.scrollIntoView({
|
||||
behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth',
|
||||
block: 'center'
|
||||
});
|
||||
const zoom = Math.max(m.getZoom(), FOCUS_ZOOM[t.scale]);
|
||||
m.once('moveend', () => {
|
||||
render();
|
||||
const pin = pins.get(slug);
|
||||
if (pin) pin.openPopup();
|
||||
else {
|
||||
const c = clusterOf.get(slug);
|
||||
if (c && L)
|
||||
L.popup(popupOptions()).setLatLng(c.at).setContent(clusterPopupHtml(c.members)).openOn(m);
|
||||
}
|
||||
});
|
||||
m.flyTo([t.lat!, t.lon!], zoom, { duration: 0.8 });
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
let disposed = false;
|
||||
let stopTiles = () => {};
|
||||
loadLeaflet()
|
||||
.then((Lf) => {
|
||||
if (disposed) return;
|
||||
L = Lf;
|
||||
const m = Lf.map(el, {
|
||||
worldCopyJump: true,
|
||||
scrollWheelZoom: false,
|
||||
minZoom: 1,
|
||||
maxZoom: 18,
|
||||
zoomSnap: 0.5
|
||||
});
|
||||
map = m;
|
||||
stopTiles = addThemedTiles(Lf, m);
|
||||
layer = Lf.layerGroup().addTo(m);
|
||||
// Scroll zoom only after the map is clicked or focused, so the page keeps scrolling.
|
||||
const on = () => {
|
||||
m.scrollWheelZoom.enable();
|
||||
scrollOn = true;
|
||||
};
|
||||
const off = () => {
|
||||
m.scrollWheelZoom.disable();
|
||||
scrollOn = false;
|
||||
};
|
||||
m.on('click focus', on);
|
||||
m.on('blur', off);
|
||||
el.addEventListener('mouseleave', off);
|
||||
m.on('zoomend', render);
|
||||
untrack(fit);
|
||||
render();
|
||||
ready = true;
|
||||
})
|
||||
.catch(() => (failed = true));
|
||||
return () => {
|
||||
disposed = true;
|
||||
stopTiles();
|
||||
map?.remove();
|
||||
map = null;
|
||||
layer = null;
|
||||
};
|
||||
});
|
||||
|
||||
// Live updates and filter changes re-render the pins; only filter changes refit the view.
|
||||
$effect(() => {
|
||||
void located;
|
||||
void catBySlug;
|
||||
if (ready) untrack(render);
|
||||
});
|
||||
let lastFit = untrack(() => fitKey);
|
||||
$effect(() => {
|
||||
const k = fitKey;
|
||||
if (!ready || k === lastFit) return;
|
||||
lastFit = k;
|
||||
untrack(fit);
|
||||
});
|
||||
$effect(() => {
|
||||
const h = highlight;
|
||||
if (!ready) return;
|
||||
untrack(() => {
|
||||
for (const e of el.querySelectorAll('.wt-hl')) e.classList.remove('wt-hl');
|
||||
if (h) shownBy.get(h)?.classList.add('wt-hl');
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="wt-map-wrap">
|
||||
<div
|
||||
class="wt-map"
|
||||
bind:this={el}
|
||||
role="region"
|
||||
aria-label="Map of tasks. Each pin is a button; the list below has every task too."
|
||||
></div>
|
||||
{#if failed}
|
||||
<p class="overlay">The map could not load. The list below has every task.</p>
|
||||
{:else if ready && !scrollOn}
|
||||
<span class="hint" aria-hidden="true">Click the map to zoom with scroll</span>
|
||||
{/if}
|
||||
<details class="legend">
|
||||
<summary>Legend</summary>
|
||||
<div class="legend-body">
|
||||
<ul aria-label="Categories">
|
||||
{#each usedCats as c (c.slug)}
|
||||
<li><i class="dot" style="background:{c.colour}"></i>{c.label}</li>
|
||||
{/each}
|
||||
</ul>
|
||||
<ul aria-label="Scales" class="scales">
|
||||
{#each WORLDTODO_SCALES.filter((s) => s !== 'planet') as s (s)}
|
||||
<li>
|
||||
<i class="dot size" style="--s:{PIN[s]}px"></i>{SCALE_INFO[s].label}
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
<ul aria-label="Pin styles">
|
||||
<li><i class="dot ring"></i>In progress</li>
|
||||
<li><i class="dot done"></i>Done</li>
|
||||
<li><i class="dot approx"></i>Approximate (region, country)</li>
|
||||
</ul>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
/* Keyless fallback (OSM tiles) darkened to sit in the dark theme. */
|
||||
:global(.wt-tiles-dim) {
|
||||
filter: invert(1) hue-rotate(180deg) brightness(0.85) contrast(0.9) saturate(0.6);
|
||||
}
|
||||
.wt-map-wrap {
|
||||
position: relative;
|
||||
border: 1px solid var(--site-border);
|
||||
border-radius: 0.85rem;
|
||||
overflow: hidden;
|
||||
background: var(--site-surface);
|
||||
}
|
||||
.wt-map {
|
||||
height: min(70vh, 720px);
|
||||
min-height: 320px;
|
||||
background: #0e0e0e;
|
||||
z-index: 0;
|
||||
}
|
||||
:global(html:not(.dark)) .wt-map {
|
||||
background: #e9e9e9;
|
||||
}
|
||||
.hint,
|
||||
.overlay {
|
||||
position: absolute;
|
||||
top: 0.6rem;
|
||||
right: 0.6rem;
|
||||
z-index: 500;
|
||||
padding: 0.2rem 0.6rem;
|
||||
border-radius: 999px;
|
||||
font-size: 0.72rem;
|
||||
color: var(--site-muted);
|
||||
background: color-mix(in srgb, var(--site-bg) 85%, transparent);
|
||||
border: 1px solid var(--site-border);
|
||||
pointer-events: none;
|
||||
}
|
||||
.overlay {
|
||||
inset: 40% 1rem auto;
|
||||
text-align: center;
|
||||
}
|
||||
.legend {
|
||||
position: absolute;
|
||||
left: 0.6rem;
|
||||
bottom: 1.6rem;
|
||||
z-index: 500;
|
||||
max-width: calc(100% - 1.2rem);
|
||||
padding: 0.35rem 0.7rem;
|
||||
border: 1px solid var(--site-border);
|
||||
border-radius: 0.7rem;
|
||||
background: color-mix(in srgb, var(--site-bg) 90%, transparent);
|
||||
backdrop-filter: blur(6px);
|
||||
font-size: 0.75rem;
|
||||
color: var(--site-text);
|
||||
}
|
||||
.legend summary {
|
||||
cursor: pointer;
|
||||
font-weight: 600;
|
||||
}
|
||||
.legend-body {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.4rem 1.2rem;
|
||||
padding: 0.4rem 0 0.15rem;
|
||||
max-height: 40vh;
|
||||
overflow: auto;
|
||||
}
|
||||
.legend ul {
|
||||
display: grid;
|
||||
gap: 0.2rem;
|
||||
align-content: start;
|
||||
}
|
||||
.legend li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
color: var(--site-muted);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.dot {
|
||||
display: inline-block;
|
||||
width: 0.7rem;
|
||||
height: 0.7rem;
|
||||
border-radius: 999px;
|
||||
border: 1.5px solid #fff;
|
||||
flex: none;
|
||||
}
|
||||
.dot.size {
|
||||
width: calc(var(--s) * 0.6);
|
||||
height: calc(var(--s) * 0.6);
|
||||
background: var(--site-muted);
|
||||
}
|
||||
.dot.ring {
|
||||
background: #737373;
|
||||
box-shadow: 0 0 0 2px #facc15;
|
||||
}
|
||||
.dot.done {
|
||||
background: #525252;
|
||||
border-color: #a3a3a3;
|
||||
}
|
||||
.dot.approx {
|
||||
background: #737373;
|
||||
outline: 1.5px dashed #a3a3a3;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
/* Leaflet-made DOM (pins, clusters, popups) lives inside .wt-map. */
|
||||
.wt-map :global(.wt-pin-wrap) {
|
||||
background: none;
|
||||
border: 0;
|
||||
border-radius: 999px;
|
||||
}
|
||||
.wt-map :global(.wt-pin-wrap:focus-visible) {
|
||||
outline: 2px solid #fff;
|
||||
outline-offset: 3px;
|
||||
}
|
||||
.wt-map :global(.wt-pin) {
|
||||
position: relative;
|
||||
box-sizing: border-box;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: var(--s);
|
||||
height: var(--s);
|
||||
border-radius: 999px;
|
||||
background: var(--c);
|
||||
border: 2px solid #fff;
|
||||
color: #fff;
|
||||
box-shadow: 0 2px 8px rgb(0 0 0 / 0.55);
|
||||
cursor: pointer;
|
||||
transition: transform 0.15s;
|
||||
}
|
||||
.wt-map :global(.wt-pin svg) {
|
||||
width: 62%;
|
||||
height: 62%;
|
||||
}
|
||||
.wt-map :global(.wt-pin.approximate) {
|
||||
outline: 2px dashed color-mix(in srgb, var(--c) 60%, #fff);
|
||||
outline-offset: 3px;
|
||||
}
|
||||
.wt-map :global(.wt-pin.done) {
|
||||
background: #4b4b4b;
|
||||
border-color: #a3a3a3;
|
||||
color: #e5e5e5;
|
||||
opacity: 0.85;
|
||||
}
|
||||
.wt-map :global(.wt-pin.in_progress::after) {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: -5px;
|
||||
border-radius: 999px;
|
||||
border: 2px solid var(--c);
|
||||
animation: wt-pulse 1.8s ease-out infinite;
|
||||
pointer-events: none;
|
||||
}
|
||||
@keyframes -global-wt-pulse {
|
||||
from {
|
||||
transform: scale(0.85);
|
||||
opacity: 0.95;
|
||||
}
|
||||
to {
|
||||
transform: scale(1.7);
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
.wt-map :global(.wt-pin-wrap:hover .wt-pin),
|
||||
.wt-map :global(.wt-pin-wrap:focus-visible .wt-pin),
|
||||
.wt-map :global(.wt-hl .wt-pin),
|
||||
.wt-map :global(.wt-pin-wrap:hover .wt-cluster),
|
||||
.wt-map :global(.wt-hl .wt-cluster) {
|
||||
transform: scale(1.35);
|
||||
}
|
||||
.wt-map :global(.wt-pin-wrap.wt-hl) {
|
||||
z-index: 10000 !important;
|
||||
}
|
||||
.wt-map :global(.wt-hl .wt-pin) {
|
||||
box-shadow:
|
||||
0 0 0 3px #fff,
|
||||
0 2px 12px rgb(0 0 0 / 0.6);
|
||||
}
|
||||
.wt-map :global(.wt-cluster) {
|
||||
box-sizing: border-box;
|
||||
display: flex;
|
||||
width: var(--s);
|
||||
height: var(--s);
|
||||
padding: 3px;
|
||||
border-radius: 999px;
|
||||
box-shadow: 0 2px 10px rgb(0 0 0 / 0.55);
|
||||
cursor: pointer;
|
||||
transition: transform 0.15s;
|
||||
}
|
||||
.wt-map :global(.wt-cluster span) {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 999px;
|
||||
background: #0a0a0a;
|
||||
color: #fff;
|
||||
font-size: 0.78rem;
|
||||
font-weight: 650;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.wt-map :global(.leaflet-control-attribution) {
|
||||
background: color-mix(in srgb, var(--site-bg) 80%, transparent);
|
||||
color: var(--site-muted);
|
||||
font-size: 0.65rem;
|
||||
}
|
||||
.wt-map :global(.leaflet-control-attribution a) {
|
||||
color: var(--site-text);
|
||||
}
|
||||
.wt-map :global(.leaflet-control-zoom) {
|
||||
border: 1px solid var(--site-border);
|
||||
border-radius: 0.6rem;
|
||||
overflow: hidden;
|
||||
}
|
||||
.wt-map :global(.leaflet-control-zoom a) {
|
||||
background: var(--site-bg);
|
||||
color: var(--site-text);
|
||||
border-color: var(--site-border);
|
||||
}
|
||||
.wt-map :global(.wt-popup .leaflet-popup-content-wrapper),
|
||||
.wt-map :global(.wt-popup .leaflet-popup-tip) {
|
||||
background: var(--site-surface);
|
||||
color: var(--site-text);
|
||||
border: 1px solid var(--site-border);
|
||||
box-shadow: 0 12px 32px -12px rgb(0 0 0 / 0.7);
|
||||
}
|
||||
.wt-map :global(.wt-popup .leaflet-popup-content-wrapper) {
|
||||
border-radius: 0.85rem;
|
||||
}
|
||||
.wt-map :global(.wt-popup .leaflet-popup-content) {
|
||||
margin: 0.8rem 0.9rem;
|
||||
font: inherit;
|
||||
}
|
||||
.wt-map :global(.wt-popup a.leaflet-popup-close-button) {
|
||||
color: var(--site-muted);
|
||||
}
|
||||
.wt-map :global(.wt-pop) {
|
||||
display: grid;
|
||||
gap: 0.4rem;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
.wt-map :global(.wt-chips) {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.3rem;
|
||||
padding-right: 1rem;
|
||||
}
|
||||
.wt-map :global(.wt-chip),
|
||||
.wt-map :global(.wt-status) {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.3rem;
|
||||
padding: 0.05rem 0.45rem;
|
||||
border: 1px solid var(--site-border);
|
||||
border-radius: 999px;
|
||||
font-size: 0.7rem;
|
||||
color: var(--site-muted);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.wt-map :global(.wt-chip i),
|
||||
.wt-map :global(.wt-list i) {
|
||||
width: 0.55rem;
|
||||
height: 0.55rem;
|
||||
border-radius: 999px;
|
||||
flex: none;
|
||||
}
|
||||
.wt-map :global(.wt-status) {
|
||||
color: var(--site-text);
|
||||
}
|
||||
.wt-map :global(.wt-status.done) {
|
||||
background: var(--site-text);
|
||||
color: var(--site-bg);
|
||||
}
|
||||
.wt-map :global(.wt-title) {
|
||||
color: var(--site-text);
|
||||
font-size: 0.92rem;
|
||||
font-weight: 600;
|
||||
line-height: 1.3;
|
||||
text-decoration: none;
|
||||
}
|
||||
.wt-map :global(.wt-title:hover) {
|
||||
text-decoration: underline;
|
||||
}
|
||||
.wt-map :global(.wt-pop p) {
|
||||
margin: 0;
|
||||
}
|
||||
.wt-map :global(.wt-where) {
|
||||
color: var(--site-muted);
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
.wt-map :global(.wt-desc) {
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
color: var(--site-text);
|
||||
line-height: 1.4;
|
||||
}
|
||||
.wt-map :global(.wt-actions) {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.35rem;
|
||||
padding-top: 0.15rem;
|
||||
}
|
||||
.wt-map :global(.wt-btn) {
|
||||
padding: 0.3rem 0.7rem;
|
||||
border: 1px solid var(--site-border);
|
||||
border-radius: 999px;
|
||||
color: var(--site-text);
|
||||
font-size: 0.75rem;
|
||||
font-weight: 550;
|
||||
text-decoration: none;
|
||||
}
|
||||
.wt-map :global(.wt-btn:hover),
|
||||
.wt-map :global(.wt-btn:focus-visible) {
|
||||
border-color: var(--site-text);
|
||||
}
|
||||
.wt-map :global(.wt-btn.primary) {
|
||||
background: var(--site-text);
|
||||
color: var(--site-bg);
|
||||
border-color: var(--site-text);
|
||||
}
|
||||
.wt-map :global(.wt-list) {
|
||||
display: grid;
|
||||
gap: 0.35rem;
|
||||
max-height: 14rem;
|
||||
overflow: auto;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
.wt-map :global(.wt-list li) {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
.wt-map :global(.wt-list a) {
|
||||
flex: 1;
|
||||
color: var(--site-text);
|
||||
text-decoration: none;
|
||||
line-height: 1.3;
|
||||
}
|
||||
.wt-map :global(.wt-list a:hover) {
|
||||
text-decoration: underline;
|
||||
}
|
||||
@media (max-width: 640px) {
|
||||
.wt-map {
|
||||
height: 60vh;
|
||||
}
|
||||
.hint {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.wt-map :global(.wt-pin.in_progress::after) {
|
||||
animation: none;
|
||||
transform: scale(1.25);
|
||||
}
|
||||
.wt-map :global(.wt-pin),
|
||||
.wt-map :global(.wt-cluster) {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
40
src/lib/worldtodo/cluster.test.ts
Normal file
40
src/lib/worldtodo/cluster.test.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { clusterPoints, coordKey, ringOffsets } from './cluster';
|
||||
|
||||
const pt = (x: number, y: number, weight = 1) => ({ x, y, weight });
|
||||
|
||||
describe('clusterPoints', () => {
|
||||
it('groups points within the radius and keeps far ones apart', () => {
|
||||
const a = pt(0, 0);
|
||||
const b = pt(10, 10);
|
||||
const c = pt(200, 0);
|
||||
const groups = clusterPoints([a, b, c], 40);
|
||||
expect(groups).toHaveLength(2);
|
||||
expect(groups.find((g) => g.includes(a))).toContain(b);
|
||||
expect(groups.find((g) => g.includes(c))).toEqual([c]);
|
||||
});
|
||||
it('lets the heaviest point anchor the cluster', () => {
|
||||
const small = pt(0, 0, 1);
|
||||
const big = pt(30, 0, 5);
|
||||
const far = pt(65, 0, 1);
|
||||
const groups = clusterPoints([small, big, far], 40);
|
||||
expect(groups[0][0]).toBe(big);
|
||||
expect(groups[0]).toHaveLength(3);
|
||||
});
|
||||
it('radius 0 keeps every point alone', () => {
|
||||
expect(clusterPoints([pt(0, 0), pt(0, 0)], 0)).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ringOffsets', () => {
|
||||
it('is a no-op for one pin and spreads several pins apart', () => {
|
||||
expect(ringOffsets(1)).toEqual([{ dx: 0, dy: 0 }]);
|
||||
const ring = ringOffsets(4);
|
||||
expect(ring).toHaveLength(4);
|
||||
const keys = new Set(ring.map((o) => `${o.dx},${o.dy}`));
|
||||
expect(keys.size).toBe(4);
|
||||
});
|
||||
it('rounds coordinates for grouping', () => {
|
||||
expect(coordKey(52.2, 5.3)).toBe(coordKey(52.20001, 5.30002));
|
||||
});
|
||||
});
|
||||
45
src/lib/worldtodo/cluster.ts
Normal file
45
src/lib/worldtodo/cluster.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
// Tiny screen-space clustering for the task map (a few hundred pins at most, so O(n²) is fine
|
||||
// and avoids a plugin). Points are in projected pixels at the current zoom.
|
||||
|
||||
export type ScreenPoint = { x: number; y: number; weight: number };
|
||||
|
||||
/**
|
||||
* Greedy clustering: the heaviest unassigned point (largest scale) takes every unassigned
|
||||
* point within `radius` px. Returns groups in that order; radius 0 keeps every point alone.
|
||||
*/
|
||||
export function clusterPoints<T extends ScreenPoint>(points: T[], radius: number): T[][] {
|
||||
const order = [...points].sort((a, b) => b.weight - a.weight);
|
||||
const used = new Set<T>();
|
||||
const groups: T[][] = [];
|
||||
const r2 = radius * radius;
|
||||
for (const p of order) {
|
||||
if (used.has(p)) continue;
|
||||
used.add(p);
|
||||
const group = [p];
|
||||
if (radius > 0)
|
||||
for (const q of order) {
|
||||
if (used.has(q)) continue;
|
||||
const dx = q.x - p.x;
|
||||
const dy = q.y - p.y;
|
||||
if (dx * dx + dy * dy <= r2) {
|
||||
used.add(q);
|
||||
group.push(q);
|
||||
}
|
||||
}
|
||||
groups.push(group);
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
|
||||
/** Offsets (px) that fan out `n` pins sharing one coordinate in a small ring. */
|
||||
export function ringOffsets(n: number): { dx: number; dy: number }[] {
|
||||
if (n <= 1) return [{ dx: 0, dy: 0 }];
|
||||
const r = 16 + n * 3;
|
||||
return Array.from({ length: n }, (_, i) => {
|
||||
const a = (2 * Math.PI * i) / n - Math.PI / 2;
|
||||
return { dx: Math.round(Math.cos(a) * r), dy: Math.round(Math.sin(a) * r) };
|
||||
});
|
||||
}
|
||||
|
||||
/** Rounded lat/lon key, so tasks on the same centroid can be fanned out. */
|
||||
export const coordKey = (lat: number, lon: number) => `${lat.toFixed(4)},${lon.toFixed(4)}`;
|
||||
@@ -8,6 +8,19 @@ export const WORLDTODO_REQUEST_KINDS = ['add', 'edit', 'delete'] as const;
|
||||
export type RequestKind = (typeof WORLDTODO_REQUEST_KINDS)[number];
|
||||
export const WORLDTODO_REQUEST_STATUSES = ['pending', 'approved', 'rejected'] as const;
|
||||
export type RequestStatus = (typeof WORLDTODO_REQUEST_STATUSES)[number];
|
||||
export const WORLDTODO_LOCATION_PRECISIONS = ['exact', 'approximate', 'none'] as const;
|
||||
export type LocationPrecision = (typeof WORLDTODO_LOCATION_PRECISIONS)[number];
|
||||
|
||||
/** Same rule as the tasks_location_precision trigger: what kind of pin a task gets. */
|
||||
export function precisionFor(
|
||||
scale: Scale,
|
||||
lat: number | null | undefined,
|
||||
lon: number | null | undefined
|
||||
): LocationPrecision {
|
||||
if (lat === null || lat === undefined || lon === null || lon === undefined) return 'none';
|
||||
if (scale === 'planet') return 'none';
|
||||
return scale === 'street' || scale === 'city' ? 'exact' : 'approximate';
|
||||
}
|
||||
|
||||
/** The only keys a request payload may carry (checked server-side). */
|
||||
export const EDITABLE_FIELDS = [
|
||||
@@ -66,6 +79,8 @@ export type PublicTask = {
|
||||
countryCode: string | null;
|
||||
lat: number | null;
|
||||
lon: number | null;
|
||||
/** Map pin kind (see precisionFor). */
|
||||
locationPrecision: LocationPrecision;
|
||||
status: Status;
|
||||
sourceUrls: string[];
|
||||
sourceDate: string | null;
|
||||
|
||||
54
src/lib/worldtodo/tiles.ts
Normal file
54
src/lib/worldtodo/tiles.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import type * as Leaflet from 'leaflet';
|
||||
import { PUBLIC_MAPTILER_API_KEY } from '$app/env/public';
|
||||
|
||||
// MapTiler "Dataviz" basemaps on OpenStreetMap data (the site's existing public MapTiler
|
||||
// key): dark in the dark theme, light in the light one, swapped live when the theme
|
||||
// toggles. Without a key (local dev) it falls back to the standard OSM tiles, darkened
|
||||
// with a CSS filter in the dark theme. CARTO's raster tiles need a key since Sept 2026.
|
||||
|
||||
const isDark = () => document.documentElement.classList.contains('dark');
|
||||
|
||||
const OSM =
|
||||
'© <a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noopener">OpenStreetMap</a> contributors';
|
||||
const MAPTILER =
|
||||
'© <a href="https://www.maptiler.com/copyright/" target="_blank" rel="noopener">MapTiler</a>';
|
||||
|
||||
function source(dark: boolean): { url: string; attribution: string; filtered: boolean } {
|
||||
if (PUBLIC_MAPTILER_API_KEY) {
|
||||
const style = dark ? 'dataviz-dark' : 'dataviz';
|
||||
return {
|
||||
url: `https://api.maptiler.com/maps/${style}/256/{z}/{x}/{y}{r}.png?key=${encodeURIComponent(PUBLIC_MAPTILER_API_KEY)}`,
|
||||
attribution: `${MAPTILER} ${OSM}`,
|
||||
filtered: false
|
||||
};
|
||||
}
|
||||
return {
|
||||
url: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
|
||||
attribution: OSM,
|
||||
filtered: dark
|
||||
};
|
||||
}
|
||||
|
||||
/** Adds the themed tile layer to `map`; returns a cleanup for the theme observer. */
|
||||
export function addThemedTiles(L: typeof Leaflet, map: Leaflet.Map): () => void {
|
||||
const first = source(isDark());
|
||||
const layer = L.tileLayer(first.url, {
|
||||
maxZoom: 19,
|
||||
attribution: first.attribution,
|
||||
className: first.filtered ? 'wt-tiles-dim' : ''
|
||||
}).addTo(map);
|
||||
const apply = () => {
|
||||
const s = source(isDark());
|
||||
layer.getContainer()?.classList.toggle('wt-tiles-dim', s.filtered);
|
||||
layer.setUrl(s.url);
|
||||
};
|
||||
const observer = new MutationObserver(apply);
|
||||
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });
|
||||
return () => observer.disconnect();
|
||||
}
|
||||
|
||||
/** Leaflet is browser-only: load it on demand (never during SSR). */
|
||||
export async function loadLeaflet(): Promise<typeof Leaflet> {
|
||||
const mod = await import('leaflet');
|
||||
return (mod.default ?? mod) as typeof Leaflet;
|
||||
}
|
||||
Reference in New Issue
Block a user