git clone https://garage44.eu/jeroen/cartopolis.git.. /crates/atlas/web/src/lib/feeds.ts
import type {FeedDataset, FeedDef, FeedListed, FeedPreview} from '@/types'
import {api, notifier} from '@/app'
import {ApiError} from '@/lib/api'
/**
* Data layers (`docs/notes/data-layers.md`, `docs/mockups/data-layers/` sheet 2):
* records from a source outside Cartopolis that atlas places on the map and keeps
* current. TripleXL's saved queries first. A layer is a definition — a source, the
* columns that place, title and colour a record, and the ones its card shows —
* kept by atlas under `/api/pipeline/feeds`; saving one refreshes it at once.
*/
/** The colours the app gives a layer's values, in rank order, then "other"
* (`systems::feeds::PALETTE` in the client: keep the two the same). */
export const PALETTE = ['#5fb3e6', '#f2a33a', '#b48cf0', '#7fc9a0', '#e8893c', '#e5d36a', '#e57aa0', '#9aa7ab']
export function colour(value: number): string {
return value < 0 ? PALETTE[0] : PALETTE[Math.min(value, PALETTE.length - 1)]
}
function report(e: unknown, fallback: string) {
if (e instanceof ApiError) {
if (!e.isUnauthorized) {
notifier.error(e.message)
}
return
}
notifier.error(fallback)
}
/** A layer id from its name and source: lower case, digits and dashes, 40 at most. */
export function slug(text: string): string {
return text
.normalize('NFD')
.replace(/[̀-ͯ]/g, '')
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 40)
.replace(/-+$/, '')
}
/** A short publisher id for the layer id: "Waterschap Noorderzijlvest" → "noorderzijlvest". */
export function publisherSlug(dataset: string): string {
const last = dataset.replace(/\/+$/, '').split('/').pop() ?? ''
return slug(last)
}
/**
* The preview's points in a box of `w` × `h`: longitude scaled by the cosine of the
* middle latitude, so a square on the ground is square on the screen, fitted with
* a margin. Returns `[x, y, value]`.
*/
export function project(points: [number, number, number][], w: number, h: number, margin = 12): [number, number, number][] {
if (!points.length) {
return []
}
const lats = points.map((p) => p[0])
const lngs = points.map((p) => p[1])
const [s, n] = [Math.min(...lats), Math.max(...lats)]
const [west, east] = [Math.min(...lngs), Math.max(...lngs)]
const k = Math.cos((((s + n) / 2) * Math.PI) / 180)
const spanX = Math.max((east - west) * k, 1e-6)
const spanY = Math.max(n - s, 1e-6)
const scale = Math.min((w - 2 * margin) / spanX, (h - 2 * margin) / spanY)
const ox = (w - spanX * scale) / 2
const oy = (h - spanY * scale) / 2
return points.map(([lat, lng, v]) => [ox + (lng - west) * k * scale, oy + (n - lat) * scale, v])
}
/** When something happened, in words: "28 Nov 2026, 17:42". */
export function when(ms: number): string {
if (!ms) {
return 'never'
}
return new Date(ms).toLocaleString('en-GB', {day: 'numeric', hour: '2-digit', minute: '2-digit', month: 'short', year: 'numeric'})
}
export async function loadFeeds(): Promise<FeedListed[] | null> {
try {
const r = await api.get<{feeds: FeedListed[]}>('/api/pipeline/feeds')
return r.feeds
} catch (e) {
report(e, 'Could not load the data layers')
return null
}
}
export async function inspect(url: string): Promise<FeedDataset | null> {
try {
const r = await api.post<{dataset: FeedDataset}>('/api/pipeline/feeds/inspect', {url})
return r.dataset
} catch (e) {
report(e, 'Could not read that dataset')
return null
}
}
export async function preview(dataset: string, query: string, colourBy: string): Promise<FeedPreview | null> {
try {
const r = await api.post<{preview: FeedPreview}>('/api/pipeline/feeds/preview', {
colour_by: colourBy,
source: {dataset, kind: 'triplexl', query},
})
return r.preview
} catch (e) {
report(e, 'Could not ask that query')
return null
}
}
/** Save and refresh a layer. The answer says whether the source answered. */
export async function saveFeed(def: FeedDef): Promise<FeedListed | null> {
try {
const r = await api.put<{feed: FeedListed | null; error: string | null}>(`/api/pipeline/feeds/${def.id}`, def)
if (r.error) {
notifier.error(`Saved ${def.name}, but the source did not answer: ${r.error}`)
} else if (r.feed) {
notifier.success(`Published ${def.name}: ${r.feed.state.placed.toLocaleString()} records on the map`)
}
return r.feed
} catch (e) {
report(e, 'Could not save that layer')
return null
}
}
export async function refreshFeed(id: string): Promise<boolean> {
try {
await api.post(`/api/pipeline/feeds/${id}/refresh`, {})
return true
} catch (e) {
report(e, 'Could not refresh that layer')
return false
}
}
export async function deleteFeed(id: string): Promise<boolean> {
try {
await api.delete(`/api/pipeline/feeds/${id}`)
return true
} catch (e) {
report(e, 'Could not delete that layer')
return false
}
}