garage44.eu/jeroen/cartopolis

logclone: git clone https://garage44.eu/jeroen/cartopolis.git

.. /crates/atlas/web/src/components/pages/feeds/feeds.tsx

raw

import m, {MithrilComponent} from '@garage44/mithril'
import {Badge, Button, Card, FieldCheckbox, FieldNumber, FieldSelect, FieldText} from '@garage44/mithril/components'

import type {FeedDataset, FeedDef, FeedListed, FeedPreview} from '@/types'

import {
    colour,
    deleteFeed,
    inspect,
    loadFeeds,
    preview,
    project,
    publisherSlug,
    refreshFeed,
    saveFeed,
    slug,
    when,
} from '@/lib/feeds'
import {bind, local} from '@/lib/reactive'

const MAP_W = 560
const MAP_H = 360

/** A string field of a `local()` as a select's model: the select may write `null`. */
function choice<T extends object>(s: T, key: {[K in keyof T]: T[K] extends string ? K : never}[keyof T]) {
    return {
        get value(): string | null {
            return s[key] as string
        },
        set value(v: string | null) {
            ;(s[key] as string) = v ?? ''
        },
    }
}

interface Draft {
    url: string
    dataset: FeedDataset | null
    query: string
    preview: FeedPreview | null
    name: string
    group: string
    title: string
    colour_by: string
    fields: string[]
    credit: string
    licence: string
    refresh_hours: number | null
    follow: boolean
    busy: boolean
}

function fresh(): Draft {
    return {
        busy: false,
        colour_by: '',
        credit: '',
        dataset: null,
        fields: [],
        group: '',
        licence: '',
        name: '',
        preview: null,
        query: '',
        refresh_hours: 6,
        follow: true,
        title: '',
        url: '',
    }
}

/** The preview's dots on a plain ground, north up (`lib/feeds.project`). */
function previewMap(p: FeedPreview) {
    const dots = project(p.points, MAP_W, MAP_H)
    return (
        <svg class="feeds-map" height={MAP_H} role="img" viewBox={`0 0 ${MAP_W} ${MAP_H}`} width={MAP_W}>
            <title>{`${p.placed.toLocaleString()} records`}</title>
            {dots.map(([x, y, v]) => (
                <circle cx={x.toFixed(1)} cy={y.toFixed(1)} fill={colour(v)} r="3" />
            ))}
        </svg>
    )
}

/** Adding a layer: the source, what it draws, how it shows (the mockup's sheet 2). */
class NewFeed extends MithrilComponent<{onDone: (saved: boolean) => void}> {
    d = local<Draft>(fresh())

    async look() {
        const d = this.d
        d.busy = true
        const found = await inspect(d.url)
        d.busy = false
        d.dataset = found
        d.preview = null
        if (found) {
            const first = found.queries.find((q) => q.map && !q.parameters)
            d.credit = found.name
            d.licence = found.licence
            d.group = found.publisher || found.name
            if (first) {
                d.query = first.name
                void this.ask()
            }
        }
    }

    async ask() {
        const d = this.d
        if (!d.dataset || !d.query) {
            return
        }
        const q = d.dataset.queries.find((x) => x.name === d.query)
        d.busy = true
        const p = await preview(d.dataset.dataset, d.query, d.colour_by || q?.colour || '')
        d.busy = false
        d.preview = p
        if (p) {
            const named = (c: string) => p.columns.includes(c)
            d.colour_by = d.colour_by && named(d.colour_by) ? d.colour_by : q?.colour && named(q.colour) ? q.colour : ''
            d.title = ['naam', 'name', 'titel', 'title', 'label'].find(named) ?? p.columns.find((c) => c !== p.geometry) ?? ''
            d.fields = p.columns.filter((c) => c !== p.geometry && c !== d.title && !looksLikeIri(p, c)).slice(0, 4)
            if (!d.name && q) {
                const bare = q.description.replace(/ op de kaart.*$/i, '').replace(/^De /, '') || q.name
                d.name = bare.charAt(0).toUpperCase() + bare.slice(1)
            }
        }
    }

    def(): FeedDef | null {
        const d = this.d
        if (!d.dataset || !d.preview) {
            return null
        }
        return {
            colour_by: d.colour_by,
            credit: d.credit.trim(),
            fields: d.fields,
            geometry: d.preview.geometry,
            group: d.group.trim(),
            id: slug(`${publisherSlug(d.dataset.dataset)}-${d.name}`),
            licence: d.licence.trim(),
            link: '',
            name: d.name.trim(),
            refresh_hours: d.refresh_hours ?? 6,
            follow: d.follow,
            source: {dataset: d.dataset.dataset, kind: 'triplexl', query: d.query},
            title: d.title,
        }
    }

    view(vnode: m.Vnode<{onDone: (saved: boolean) => void}>) {
        const d = this.d
        const p = d.preview
        // A new query or colour column asks the source again.
        const askAgain = () => this.ask()
        const queries = d.dataset?.queries ?? []
        const def = this.def()
        const ready = !!def && !!def.name && !!def.title && !!def.credit && !!def.group && p!.placed > 0
        const columns = p ? p.columns.filter((c) => c !== p.geometry) : []
        return (
            <div class="feeds-new">
                <Card>
                    <h3 class="feeds-step">1 · Source</h3>
                    <div class="feeds-row">
                        <FieldText
                            disabled={d.busy}
                            help="A TripleXL dataset's address, or one of its pages: https://www.triplexl.nl/datasets/{account}/{dataset}"
                            label="Address"
                            model={bind(d, 'url')}
                        />
                        <Button disabled={!d.url.trim() || d.busy} loading={d.busy && !d.dataset} onclick={() => void this.look()} variant="secondary">
                            Look it up
                        </Button>
                    </div>
                    {d.dataset && (
                        <div class="feeds-found">
                            <b>{d.dataset.name}</b> — {d.dataset.publisher}, {d.dataset.licence},{' '}
                            {d.dataset.statements.toLocaleString()} statements
                        </div>
                    )}
                    {d.dataset && (
                        <FieldSelect
                            disabled={d.busy}
                            help="Queries TripleXL marks as maps come first. One that asks for a value cannot be a layer by itself."
                            label="Query"
                            model={{
                                get value() {
                                    return d.query
                                },
                                set value(v: string | null) {
                                    d.query = v ?? ''
                                    void askAgain()
                                },
                            }}
                            options={queries.map((q) => ({
                                disabled: q.parameters > 0,
                                label: `${q.description || q.name}${q.map ? ' · map' : ''}${q.parameters ? ' · asks for a value' : ''}`,
                                value: q.name,
                            }))}
                        />
                    )}
                </Card>
                {p && (
                    <Card>
                        <h3 class="feeds-step">2 · What it draws</h3>
                        {previewMap(p)}
                        <p class="feeds-note">
                            {p.rows.toLocaleString()} records, {p.placed.toLocaleString()} with a place
                            {p.geometry ? `, from the column “${p.geometry}”` : ' — no column holds points'}
                        </p>
                        {!!p.values.length && (
                            <div class="feeds-key">
                                {p.values.map((v, i) => (
                                    <span>
                                        <i style={`background: ${colour(i)}`} />
                                        {v}
                                    </span>
                                ))}
                                {p.values.length >= 7 && (
                                    <span>
                                        <i style={`background: ${colour(7)}`} />
                                        other
                                    </span>
                                )}
                            </div>
                        )}
                    </Card>
                )}
                {p && (
                    <Card>
                        <h3 class="feeds-step">3 · How it shows</h3>
                        <FieldText label="Name" model={bind(d, 'name')} />
                        <FieldText help="Its heading in Layers ▸ Data" label="Group" model={bind(d, 'group')} />
                        <FieldSelect label="Title on the card" model={choice(d, 'title')} options={columns.map((c) => ({label: c, value: c}))} />
                        <FieldSelect
                            label="Colour by"
                            model={{
                                get value() {
                                    return d.colour_by
                                },
                                set value(v: string | null) {
                                    d.colour_by = v ?? ''
                                    void askAgain()
                                },
                            }}
                            options={[{label: 'One colour', value: ''}, ...columns.map((c) => ({label: c, value: c}))]}
                        />
                        <div class="feeds-fields">
                            <span class="feeds-label">On the card</span>
                            {columns
                                .filter((c) => c !== d.title)
                                .map((c) => (
                                    <FieldCheckbox
                                        label={c}
                                        model={{
                                            get value() {
                                                return d.fields.includes(c)
                                            },
                                            set value(on: boolean) {
                                                d.fields = on ? [...d.fields, c] : d.fields.filter((f) => f !== c)
                                            },
                                        }}
                                    />
                                ))}
                        </div>
                        <FieldCheckbox
                            help="Atlas looks at the dataset's revision every minute and asks again after a commit."
                            label="Follow the source's changes"
                            model={bind(d, 'follow')}
                        />
                        <FieldNumber label="And in any case every" model={bind(d, 'refresh_hours')} unit="hours" />
                        <FieldText help="As the source asks to be credited" label="Credit" model={bind(d, 'credit')} />
                        <FieldText label="Licence" model={bind(d, 'licence')} />
                        <div class="feeds-actions">
                            <Button
                                disabled={!ready || d.busy}
                                loading={d.busy}
                                onclick={async () => {
                                    const def = this.def()
                                    if (!def) return
                                    d.busy = true
                                    const saved = await saveFeed(def)
                                    d.busy = false
                                    if (saved) vnode.attrs.onDone(true)
                                }}
                                variant="primary"
                            >
                                Publish layer
                            </Button>
                            <Button onclick={() => vnode.attrs.onDone(false)} variant="ghost">
                                Cancel
                            </Button>
                        </div>
                    </Card>
                )}
                {!p && (
                    <div class="feeds-actions">
                        <Button onclick={() => vnode.attrs.onDone(false)} variant="ghost">
                            Cancel
                        </Button>
                    </div>
                )}
            </div>
        )
    }
}

/** A column whose sample values are all addresses: the record's own, not a field. */
function looksLikeIri(p: FeedPreview, column: string): boolean {
    const values = p.sample.map((r) => r[column]).filter(Boolean)
    return values.length > 0 && values.every((v) => /^https?:\/\//.test(v))
}

/**
 * Admin ▸ Data ▸ Data layers: the layers atlas reads from open data, and adding one
 * from a pasted address.
 */
export class Feeds extends MithrilComponent {
    s = local<{feeds: FeedListed[] | null; adding: boolean; busy: string; confirming: string}>({
        adding: false,
        busy: '',
        confirming: '',
        feeds: null,
    })

    async load() {
        this.s.feeds = (await loadFeeds()) ?? []
    }

    oninit() {
        void this.load()
    }

    view() {
        const s = this.s
        return (
            <div class="feeds">
                <div class="feeds-head">
                    <span class="feeds-count">{s.feeds === null ? '' : `${s.feeds.length} ${s.feeds.length === 1 ? 'layer' : 'layers'}`}</span>
                    <span class="feeds-spacer" />
                    {!s.adding && (
                        <Button
                            onclick={() => {
                                s.adding = true
                            }}
                            variant="primary"
                        >
                            Add a data layer
                        </Button>
                    )}
                </div>
                <p class="feeds-note">
                    Records from open data, placed on the map under Layers ▸ Data. Atlas asks the source on each layer's
                    clock and sends viewers only the parts of the map that changed.
                </p>
                {s.adding && (
                    <NewFeed
                        onDone={(saved) => {
                            s.adding = false
                            if (saved) void this.load()
                        }}
                    />
                )}
                {s.feeds === null ? (
                    <p class="feeds-empty">Loading…</p>
                ) : !s.feeds.length ? (
                    <p class="feeds-empty">No data layer yet.</p>
                ) : (
                    <Card flush>
                        <ul class="feeds-list">
                            {s.feeds.map(({def, state}) => (
                                <li class="feeds-item" key={def.id}>
                                    <div class="feeds-item__main">
                                        <span class="feeds-name">{def.name}</span>
                                        <span class="feeds-group">{def.group}</span>
                                        {state.error ? <Badge tone="danger">source failed</Badge> : <Badge tone="success">{`${state.placed.toLocaleString()} records`}</Badge>}
                                        <span class="feeds-spacer" />
                                        <Button
                                            disabled={!!s.busy}
                                            loading={s.busy === def.id}
                                            onclick={async () => {
                                                s.busy = def.id
                                                await refreshFeed(def.id)
                                                s.busy = ''
                                                void this.load()
                                            }}
                                            size="sm"
                                            variant="ghost"
                                        >
                                            Refresh now
                                        </Button>
                                        {s.confirming === def.id ? (
                                            <Button
                                                onclick={async () => {
                                                    s.confirming = ''
                                                    if (await deleteFeed(def.id)) void this.load()
                                                }}
                                                size="sm"
                                                variant="danger"
                                            >
                                                Really delete
                                            </Button>
                                        ) : (
                                            <Button
                                                onclick={() => {
                                                    s.confirming = def.id
                                                }}
                                                size="sm"
                                                variant="ghost"
                                            >
                                                Delete
                                            </Button>
                                        )}
                                    </div>
                                    <div class="feeds-meta">
                                        {def.source.dataset.replace(/^https:\/\//, '')} · {def.source.query} ·{' '}
                                        {def.follow ? 'follows its changes, and ' : ''}every {def.refresh_hours} h · asked {when(state.tried_ms)} · changed {when(state.changed_ms)}
                                    </div>
                                    {state.error && <div class="feeds-error">{state.error}</div>}
                                </li>
                            ))}
                        </ul>
                    </Card>
                )}
            </div>
        )
    }
}