import m from '@garage44/mithril' import {Button, Card, FieldSwitch, FieldText} from '@garage44/mithril/components' import {askConfirm} from '@/components/confirm' import {act} from '@/lib/actions' import {api} from '@/lib/api' import type {ProjectGraph, RepoAbout, RepoEntry, TreeState} from '@/lib/api' import {markdown} from '@/lib/markdown' import {bind} from '@/lib/reactive' import {$s} from '@/lib/store' import {local} from '@/lib/reactive' import {go} from '@/lib/route' import {hosted, type Hosted} from '@/lib/stream' import {reposOf, show} from '@/lib/projects' /** * Goals ▸ Map (docs/screens/graph.html): every project at once, which one's code another uses, the * sessions between them; and, zoomed in, one project's sessions over time beside the projects it is * built on. The map is drawn by the hub (graph.rs `svg`, the same drawing the public front page shows); * the week is drawn here from the sessions the page already follows. */ const state = local({ graph: null as ProjectGraph | null, svg: '', error: '', loading: false, picked: '', days: 7, /** Each project's about (how to get it, its settings), and each directory or file read, by `repo:path`. */ about: {} as Record, files: {} as Record, /** The settings form, for the project it was filled from. */ form: {repo: '', description: '', public: false, main: '', gate: '', gate_nodes: '', pre_land: '', name: ''}, }) function load() { if (state.loading) return state.loading = true api.graph() .then((r) => { state.graph = r.graph state.svg = r.svg state.error = '' }) .catch((e: Error) => (state.error = e.message)) .finally(() => (state.loading = false)) } const short = (repo: string) => repo.split('/').pop() ?? repo /** What `p` is built on, and what is built on it, by code. */ const usesOf = (g: ProjectGraph, p: string) => [...new Set(g.code.filter((c) => c.to === p).map((c) => c.from))] const usedBy = (g: ProjectGraph, p: string) => [...new Set(g.code.filter((c) => c.from === p).map((c) => c.to))] /** Pins further behind than this are worth a word, as the map draws them amber. */ const STALE = 5 function pickedCard(g: ProjectGraph, name: string): m.Children { const p = g.projects.find((x) => x.name === name) if (!p) return null const uses = usesOf(g, name) const by = usedBy(g, name) const stale = g.code.filter((c) => c.from === name && (c.behind ?? 0) > STALE) const shared = g.shared .filter((s) => s.a === name || s.b === name) .map((s) => ({other: s.a === name ? s.b : s.a, n: s.n})) .sort((a, b) => b.n - a.n) return (
{uses.length ? [
uses
,
{uses.map(short).join(' · ')}
] : null} {by.length ? [
used by
,
{by.map(short).join(' · ')}
] : null}
sessions
{p.sessions ?? 0} {shared.length ? ` · most shared with ${shared.slice(0, 2).map((s) => `${short(s.other)} (${s.n})`).join(', ')}` : ''}
{p.techs ? [
techs
,
{p.built} of {p.techs} built
] : null}
{stale.map((c) => (

⚑ {short(c.to)} uses a commit {c.behind} behind ({c.file})

))}
{p.techs ? ( ) : null}
) } /** On a phone: the projects as a list, in the map's columns, each saying what it uses and what uses it. */ function mapList(g: ProjectGraph): m.Children { const linked = new Set(g.code.flatMap((c) => [c.from, c.to])) // The columns of the map, those that share no code (graph.rs wraps them over several) as one. const apart = g.projects.filter((p) => !linked.has(p.name)) const cols = [...new Set(g.projects.filter((p) => linked.has(p.name)).map((p) => p.col))].sort((a, b) => a - b) const groups: [string, typeof apart][] = [ ...cols.map((c): [string, typeof apart] => [c === cols[0] ? 'Built on no other project' : 'Built on the ones above', g.projects.filter((p) => p.col === c && linked.has(p.name))]), ...(apart.length ? [['No code shared', apart] as [string, typeof apart]] : []), ] return (
{groups.map(([title, list]) => [ {title}, list .slice() .sort((a, b) => a.col - b.col || a.row - b.row) .map((p) => [ , // On a phone the tapped one opens under itself, not past the end of the list. state.picked === p.name ? pickedCard(g, p.name) : null, ]), ])}
) } function mapPage(): m.Children { const g = state.graph! return (
Map {g.projects.length} projects · which uses which, and the sessions between them
{ const p = (e.target as Element).closest('[data-project]')?.getAttribute('data-project') ?? '' state.picked = state.picked === p ? '' : p }} onkeydown={(e: KeyboardEvent) => { if (e.key !== 'Enter') return state.picked = (e.target as Element).closest('[data-project]')?.getAttribute('data-project') ?? '' }} > {m.trust(state.svg)}
{mapList(g)}
{state.picked ? pickedCard(g, state.picked) : null}
uses its code, arrow from the one used uses an older commit sessions in both, thicker for more a tech there needs one here size: sessions · ring: techs built
) } type Outcome = 'landed' | 'ended' | 'working' /** The session `h` was started from (`from`), or whose branch it was started on (its `base`). */ const parentOf = (h: Hosted): string | null => h.from ?? h.base?.match(/^session\/(s\d+)$/)?.[1] ?? null function outcomeOf(h: Hosted): Outcome { if (h.finished?.outcome === 'landed') return 'landed' if (h.finished || h.status === 'stopped' || h.status === 'failed') return 'ended' return 'working' } const X0 = 150 const W = 1100 const LANE = 13 /** * One project's sessions over time: a stream for it, then for each project it uses or that uses it, then * for each other project three or more of these sessions also worked in, then one for everywhere else. A session is a bar from its start to its end in the * first of its projects shown, with a tie to each other project it worked in. ◆: it built a tech. A * dashed curve runs to a session from the one that started it (`from`) or whose branch it began on. */ function timeTab(d: TreeState | null, name: string): m.Children { const g = state.graph! const near = [...usesOf(g, name), ...usedBy(g, name)].filter((p, i, a) => a.indexOf(p) === i && p !== name) const now = Date.now() / 1000 const t0 = state.days ? now - state.days * 86400 : Math.min(now - 86400, ...hosted().map((h) => h.created)) const all = hosted().filter((h) => { const rs = reposOf(h) return rs.some((r) => r === name || near.includes(r)) && (h.finished?.at ?? h.updated ?? now) >= t0 }) const often: Record = {} for (const h of all) for (const r of reposOf(h)) if (r !== name && !near.includes(r)) often[r] = (often[r] ?? 0) + 1 const also = Object.keys(often) .filter((r) => often[r]! >= 3) .sort((a, b) => often[b]! - often[a]!) const streams = [name, ...near, ...also].slice(0, 8) const elsewhere = all.some((h) => reposOf(h).some((r) => !streams.includes(r))) const rows = [...streams, ...(elsewhere ? ['elsewhere'] : [])] const built = new Set((d?.techs ?? []).filter((t) => t.state === 'built').flatMap((t) => (t.sessions ?? []).filter((s) => s.outcome === 'landed').map((s) => s.id))) // Lanes first, so each stream is as tall as its busiest moment. const lanes: Record = {} const placed = all .slice() .sort((a, b) => a.created - b.created) .map((h) => { const home = reposOf(h).find((r) => streams.includes(r)) ?? 'elsewhere' const ends = (lanes[home] ??= []) const start = Math.max(h.created, t0) const end = h.finished?.at ?? (outcomeOf(h) === 'working' ? now : h.updated) let k = ends.findIndex((e) => e < start) if (k < 0) k = ends.push(0) - 1 ends[k] = end + 1800 return {h, home, k, start, end} }) const height = (s: string) => Math.max(34, 12 + (lanes[s]?.length ?? 1) * LANE) const top: Record = {} let y = 30 for (const s of rows) { top[s] = y y += height(s) + 6 } const x = (t: number) => X0 + ((t - t0) / Math.max(1, now - t0)) * W const days = Math.round((now - t0) / 86400) const ticks = Array.from({length: Math.min(days, 12) + 1}, (_, i) => t0 + (i * (now - t0)) / Math.min(days, 12)) const label = (t: number) => new Date(t * 1000).toLocaleDateString(undefined, {day: 'numeric', month: 'short'}) // Started from: from the parent's bar, at the moment the child began, to the child's start. const at = new Map(placed.map((p) => [p.h.id, p])) const lines = placed.flatMap((c) => { const from = parentOf(c.h) const p = from ? at.get(from) : undefined if (!p) return [] const cx = x(c.start) const cy = top[c.home]! + 8 + c.k * LANE + 4 const px = Math.min(Math.max(x(c.start), x(p.start)), Math.max(x(p.end), x(p.start) + 6)) const py = top[p.home]! + 8 + p.k * LANE + 4 // Starts close together: a bracket out to the left, else an S from one to the other. const mid = (px + cx) / 2 const d = cx - px < 28 ? `M${px},${py} C${px - 16},${py} ${cx - 16},${cy} ${cx},${cy}` : `M${px},${py} C${mid + 12},${py} ${mid - 12},${cy} ${cx},${cy}` return [{`${c.h.id} was started from ${p.h.id}`}] }) return (
{all.length} sessions · {all.filter((h) => outcomeOf(h) === 'landed').length} landed {[7, 30, 0].map((n) => ( ))}
{ticks.map((t) => [ , {label(t)}, ])} {rows.map((s) => [ , {s === 'elsewhere' ? 'elsewhere' : short(s)}, ])} {lines} {placed.map(({h, home, k, start, end}) => { const by = top[home]! + 8 + k * LANE const x1 = x(start) const x2 = Math.max(x(end), x1 + 6) const o = outcomeOf(h) const ties = reposOf(h) .map((r) => (streams.includes(r) ? r : 'elsewhere')) .filter((r, i, a) => r !== home && a.indexOf(r) === i) return ( go(`sessions/${h.id}`)}> {`${h.id} · ${h.title} · ${reposOf(h).map(short).join(', ')}`} {ties.map((r) => [ , , ])} {built.has(h.id) ? ◆ : null} ) })}
landed ended without landing at work │ the same session in another project started from ◆ built a tech
) } function aboutOf(repo: string): RepoAbout | {error: string} | undefined { if (!(repo in state.about)) { state.about[repo] = {error: ''} api.repoAbout(repo) .then((a) => (state.about[repo] = a)) .catch((e: Error) => (state.about[repo] = {error: e.message})) } const a = state.about[repo] return a && 'error' in a && !a.error ? undefined : a } function entryOf(repo: string, path: string): RepoEntry | {error: string} | undefined { const k = `${repo}:${path}` if (!(k in state.files)) { state.files[k] = {error: ''} api.repoShow(repo, path) .then((e) => (state.files[k] = e)) .catch((e: Error) => (state.files[k] = {error: e.message})) } const e = state.files[k] return e && 'error' in e && !e.error ? undefined : e } /** How to get the project: clone it (by key for the workspace, over https when public) or download main. */ function downloadCard(name: string, a: RepoAbout): m.Children { const https = a.public ? `${location.origin}/${name}.git` : '' const tarball = a.public ? `/${name}/archive/main.tar.gz` : `/v1/repos/${name}/archive.tar.gz?rev=main` return ( {https ? (

Anyone, with git: git clone {https}

) : null}

The workspace, by key: git clone {a.ssh}

Or download main as .tar.gz {a.head ? · at {a.head.sha.slice(0, 10)}, {a.head.subject} : null}

{a.public ? null :

A private project: the download takes your login, and the clone a key the workspace knows.

}
) } /** The project's files at main: a directory as its entries and its README, a file as text. */ function filesTab(name: string, path: string): m.Children { const a = aboutOf(name) const e = entryOf(name, path) const to = (p: string) => go(`research/map/${name}/files${p ? `/${p}` : ''}`) const parts = path ? path.split('/') : [] const readme = e && !('error' in e) && e.kind === 'dir' ? e.entries?.find((x) => x.kind === 'file' && /^readme(\.md|\.markdown|\.txt)?$/i.test(x.name)) : undefined const readmeEntry = readme ? entryOf(name, path ? `${path}/${readme.name}` : readme.name) : undefined return (
{a && !('error' in a) ? downloadCard(name, a) : null} {!e ?

Reading…

: 'error' in e ?

{e.error}

: e.kind === 'dir' ? (
{(e.entries ?? []) .slice() .sort((x, y) => (x.kind === y.kind ? x.name.localeCompare(y.name) : x.kind === 'dir' ? -1 : 1)) .map((x) => ( (ev.preventDefault(), to(path ? `${path}/${x.name}` : x.name))}> {x.kind === 'dir' ? '▸ ' : ''}{x.name}{x.kind === 'dir' ? '/' : ''} {x.size != null ? `${x.size} B` : ''} ))}
) : e.text != null ? (
{e.text}
) : (

A binary file of {e.size} bytes.

)} {readmeEntry && !('error' in readmeEntry) && readmeEntry.text ? ( {/\.(md|markdown)$/i.test(readme!.name) ? markdown(readmeEntry.text) :
{readmeEntry.text}
}
) : null}
) } /** An admin's: the description, who may read it, its main branch and how it lands (hosted.rs `set`). */ function settingsTab(name: string): m.Children { if ($s.role !== 'admin') return

A project's settings are an admin's to change.

const a = aboutOf(name) if (!a) return

Reading…

if ('error' in a) return

{a.error}

const f = state.form if (f.repo !== name) { Object.assign(f, {repo: name, description: a.description ?? '', public: a.public, main: a.project?.main ?? '', gate: a.project?.gate ?? '', gate_nodes: a.project?.gate_nodes ?? '', pre_land: a.project?.pre_land ?? '', name: short(name)}) } const save = async () => { if (f.public && !a.public) { const yes = await askConfirm({ title: `Make ${short(name)} public?`, text: 'Anyone can then read and clone it, and the public map shows it. Making it private again does not take back what was read or copied meanwhile.', yes: 'Make it public', danger: true, }) if (!yes) return } const saved = await act('settings saved', () => api.projectSet(name, {description: f.description, public: f.public, main: f.main, gate: f.gate, gate_nodes: f.gate_nodes, pre_land: f.pre_land})) if (!saved) return // Read again, and the map with it: a description or visibility shows there. delete state.about[name] f.repo = '' state.graph = null } const rename = async () => { const to = f.name.trim() if (!to || to === short(name)) return let renamed = '' const done = await act(`${short(name)} is ${to} now`, async () => (renamed = (await api.projectRename(name, to)).repo)) if (!done) return delete state.about[name] f.repo = '' state.graph = null go(`research/map/${renamed}/settings`) } const remove = async () => { const yes = await askConfirm({ title: `Delete ${short(name)}?`, text: `Its repository, every branch in it and its settings go: nothing serves it any more, and its sessions stop naming it. The hub keeps the repository aside (deleted-git in its state directory), from where only someone on the hub can put it back.`, yes: 'Delete it', danger: true, }) if (!yes) return if (!(await act(`${short(name)} deleted`, () => api.projectDelete(name)))) return delete state.about[name] f.repo = '' state.graph = null go('research/map') } return [
,
,

Deletes the project and its repository, with every branch in it.

, ] } const TABS: [string, string][] = [['', 'Over time'], ['files', 'Files'], ['settings', 'Settings']] /** One project: its sessions over time, its files and how to get it, and (an admin's) its settings. */ function projectPage(d: TreeState | null, name: string, tab: string, path: string): m.Children { const p = state.graph!.projects.find((x) => x.name === name)! const tabs = TABS.filter(([t]) => t !== 'settings' || $s.role === 'admin') return (
{short(name)} {[p.description, p.public ? 'public' : 'private'].filter(Boolean).join(' · ')}
{tabs.map(([t, label]) => ( ))}
{tab === 'files' ? filesTab(name, path) : tab === 'settings' ? settingsTab(name) : timeTab(d, name)}
) } /** * The Map's pages: `research/map`, and a project's at `research/map//`, with * `/files/` and `/settings` for its other tabs. */ export function mapView(d: TreeState | null, place: string): m.Children { if (!state.graph) { load() return

{state.error || 'Reading every project…'}

} const parts = place.replace(/^research\/map\/?/, '').split('/').filter(Boolean) const name = parts.slice(0, 2).join('/') if (parts.length >= 2 && state.graph.projects.some((p) => p.name === name)) return projectPage(d, name, parts[2] ?? '', parts.slice(3).join('/')) return mapPage() }