git clone https://garage44.eu/jeroen/midas.git.. /web/src/components/projectmap.tsx
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<string, RepoAbout | {error: string}>,
files: {} as Record<string, RepoEntry | {error: string}>,
/** 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 (
<Card class="pmap-card" title={short(name)} subtitle={[p.description, p.public ? 'public' : 'private'].filter(Boolean).join(' · ')}>
<dl class="pmap-card__facts">
{uses.length ? [<dt>uses</dt>, <dd>{uses.map(short).join(' · ')}</dd>] : null}
{by.length ? [<dt>used by</dt>, <dd>{by.map(short).join(' · ')}</dd>] : null}
<dt>sessions</dt>
<dd>
{p.sessions ?? 0}
{shared.length ? ` · most shared with ${shared.slice(0, 2).map((s) => `${short(s.other)} (${s.n})`).join(', ')}` : ''}
</dd>
{p.techs ? [<dt>techs</dt>, <dd>{p.built} of {p.techs} built</dd>] : null}
</dl>
{stale.map((c) => (
<p class="pmap-card__warn">
⚑ {short(c.to)} uses a commit {c.behind} behind ({c.file})
</p>
))}
<div class="tree-bar__row">
<Button variant="primary" onclick={() => go(`research/map/${name}`)}>
Open the project
</Button>
{p.techs ? (
<Button variant="ghost" onclick={() => {
show(name)
go('research')
}}>
Its goals
</Button>
) : null}
</div>
</Card>
)
}
/** 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 (
<div class="pmap-list">
{groups.map(([title, list]) => [
<span class="hint">{title}</span>,
list
.slice()
.sort((a, b) => a.col - b.col || a.row - b.row)
.map((p) => [
<button class={`pmap-list__p${state.picked === p.name ? ' on' : ''}`} onclick={() => (state.picked = state.picked === p.name ? '' : p.name)}>
<b>{short(p.name)}</b>
<span class="hint">{p.techs ? `${p.built} / ${p.techs} built` : `${p.sessions ?? 0} session${p.sessions === 1 ? '' : 's'}`}</span>
{usesOf(g, p.name).length ? <span>uses {usesOf(g, p.name).map(short).join(', ')}</span> : null}
{usedBy(g, p.name).length ? <span>used by {usedBy(g, p.name).map(short).join(', ')}</span> : null}
</button>,
// 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,
]),
])}
</div>
)
}
function mapPage(): m.Children {
const g = state.graph!
return (
<div class="stack">
<div class="tree-bar__row">
<Button variant="ghost" onclick={() => go('research')}>
← The tree
</Button>
<b class="tree-board__title">Map</b>
<span class="hint">{g.projects.length} projects · which uses which, and the sessions between them</span>
</div>
<div class="pmap">
<div
class="pmap__drawing"
onclick={(e: Event) => {
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)}
</div>
{mapList(g)}
<div class="pmap__beside">{state.picked ? pickedCard(g, state.picked) : null}</div>
</div>
<div class="pmap-legend hint">
<span><i class="pmap-legend__code" />uses its code, arrow from the one used</span>
<span><i class="pmap-legend__stale" />uses an older commit</span>
<span><i class="pmap-legend__shared" />sessions in both, thicker for more</span>
<span><i class="pmap-legend__needs" />a tech there needs one here</span>
<span>size: sessions · ring: techs built</span>
</div>
</div>
)
}
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<string, number> = {}
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<string, number[]> = {}
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<string, number> = {}
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 [<path d={d} class="pweek__from"><title>{`${c.h.id} was started from ${p.h.id}`}</title></path>]
})
return (
<div class="stack">
<div class="tree-bar__row">
<span class="hint">
{all.length} sessions · {all.filter((h) => outcomeOf(h) === 'landed').length} landed
</span>
<span class="pweek__range">
{[7, 30, 0].map((n) => (
<Button size="sm" variant={state.days === n ? 'secondary' : 'ghost'} onclick={() => (state.days = n)}>
{n ? `${n}D` : 'All'}
</Button>
))}
</span>
</div>
<div class="pweek">
<svg class="pweek__svg" viewBox={`0 0 ${X0 + W + 20} ${y}`}>
{ticks.map((t) => [
<line x1={x(t)} y1={18} x2={x(t)} y2={y} class="pweek__tick" />,
<text x={x(t) + 4} y={14} class="pweek__date">{label(t)}</text>,
])}
{rows.map((s) => [
<rect x={8} y={top[s]} width={X0 + W + 4} height={height(s)} rx={9} class={`pweek__stream${s === name ? ' on' : ''}`} />,
<text x={20} y={top[s]! + height(s) / 2 + 4} class={`pweek__name${s === 'elsewhere' ? ' dim' : ''}`}>{s === 'elsewhere' ? 'elsewhere' : short(s)}</text>,
])}
{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 (
<g class={`pweek__s ${o}`} onclick={() => go(`sessions/${h.id}`)}>
<title>{`${h.id} · ${h.title} · ${reposOf(h).map(short).join(', ')}`}</title>
{ties.map((r) => [
<line x1={x1 + 2} y1={by + 4} x2={x1 + 2} y2={top[r]! + height(r) / 2} class="pweek__tie" />,
<circle cx={x1 + 2} cy={top[r]! + height(r) / 2} r={3} class="pweek__dot" />,
])}
<rect x={x1} y={by} width={x2 - x1} height={9} rx={4.5} class="pweek__bar" />
{built.has(h.id) ? <text x={x2 + 3} y={by + 9} class="pweek__built">◆</text> : null}
</g>
)
})}
</svg>
</div>
<div class="pmap-legend hint">
<span><i class="pweek__key landed" />landed</span>
<span><i class="pweek__key ended" />ended without landing</span>
<span><i class="pweek__key working" />at work</span>
<span>│ the same session in another project</span>
<span><i class="pweek__key from" />started from</span>
<span>◆ built a tech</span>
</div>
</div>
)
}
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 (
<Card class="pfiles__get" title="Get it">
{https ? (
<p>
Anyone, with git: <code>git clone {https}</code>
</p>
) : null}
<p>
The workspace, by key: <code>git clone {a.ssh}</code>
</p>
<p>
Or <a href={tarball} download={`${short(name)}.tar.gz`}>download main as .tar.gz</a>
{a.head ? <span class="hint"> · at {a.head.sha.slice(0, 10)}, {a.head.subject}</span> : null}
</p>
{a.public ? null : <p class="hint">A private project: the download takes your login, and the clone a key the workspace knows.</p>}
</Card>
)
}
/** 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 (
<div class="stack">
{a && !('error' in a) ? downloadCard(name, a) : null}
<nav class="pfiles__crumbs">
<a href="#" onclick={(ev: Event) => (ev.preventDefault(), to(''))}>{short(name)}</a>
{parts.map((p, i) => [' / ', <a href="#" onclick={(ev: Event) => (ev.preventDefault(), to(parts.slice(0, i + 1).join('/')))}>{p}</a>])}
</nav>
{!e ? <p class="hint">Reading…</p> : 'error' in e ? <p class="hint">{e.error}</p> : e.kind === 'dir' ? (
<div class="pfiles__list">
{(e.entries ?? [])
.slice()
.sort((x, y) => (x.kind === y.kind ? x.name.localeCompare(y.name) : x.kind === 'dir' ? -1 : 1))
.map((x) => (
<a href="#" class="pfiles__entry" onclick={(ev: Event) => (ev.preventDefault(), to(path ? `${path}/${x.name}` : x.name))}>
<span>{x.kind === 'dir' ? '▸ ' : ''}{x.name}{x.kind === 'dir' ? '/' : ''}</span>
<span class="hint">{x.size != null ? `${x.size} B` : ''}</span>
</a>
))}
</div>
) : e.text != null ? (
<pre class="pfiles__text">{e.text}</pre>
) : (
<p class="hint">A binary file of {e.size} bytes.</p>
)}
{readmeEntry && !('error' in readmeEntry) && readmeEntry.text ? (
<Card title={readme!.name} class="pfiles__readme">
{/\.(md|markdown)$/i.test(readme!.name) ? markdown(readmeEntry.text) : <pre class="pfiles__text">{readmeEntry.text}</pre>}
</Card>
) : null}
</div>
)
}
/** 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 <p class="hint">A project's settings are an admin's to change.</p>
const a = aboutOf(name)
if (!a) return <p class="hint">Reading…</p>
if ('error' in a) return <p class="hint">{a.error}</p>
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 [
<Card title="Settings" class="pset">
<FieldText model={bind(f, 'description')} label="What it is" placeholder="One line, as the README's first" />
<FieldSwitch model={bind(f, 'public')} label="Public" help="Anyone can read and clone it, without a login, and the public map shows it." />
<FieldText model={bind(f, 'main')} label="Main branch" placeholder="main" />
<FieldText model={bind(f, 'gate')} label="Landing gate" placeholder="e.g. cargo test" help="The command a branch must pass on a node before it lands on main." />
<FieldText model={bind(f, 'gate_nodes')} label="Gate nodes" placeholder="any" help="Which nodes the gate may run on." />
<FieldText model={bind(f, 'pre_land')} label="Check before landing" placeholder="(none)" help="A command run in the session's worktree before the gate." />
<div class="tree-bar__row">
<Button variant="primary" onclick={() => void save()}>
Save
</Button>
</div>
</Card>,
<Card title="Name" class="pset">
<FieldText model={bind(f, 'name')} label="Name" help="Its repository, sessions and notes take the new name; clones of the old one keep working." />
<div class="tree-bar__row">
<Button variant="secondary" disabled={!f.name.trim() || f.name.trim() === short(name)} onclick={() => void rename()}>
Rename
</Button>
</div>
</Card>,
<Card title="Delete" class="pset">
<p class="hint">Deletes the project and its repository, with every branch in it.</p>
<div class="tree-bar__row">
<Button variant="danger" onclick={() => void remove()}>
Delete {short(name)}
</Button>
</div>
</Card>,
]
}
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 (
<div class="stack">
<div class="tree-bar__row">
<Button variant="ghost" onclick={() => go('research/map')}>
← All projects
</Button>
<b class="tree-board__title">{short(name)}</b>
<span class="hint">{[p.description, p.public ? 'public' : 'private'].filter(Boolean).join(' · ')}</span>
</div>
<div class="pproj__tabs" role="tablist">
{tabs.map(([t, label]) => (
<Button size="sm" variant={tab === t ? 'secondary' : 'ghost'} onclick={() => go(`research/map/${name}${t ? `/${t}` : ''}`)}>
{label}
</Button>
))}
</div>
{tab === 'files' ? filesTab(name, path) : tab === 'settings' ? settingsTab(name) : timeTab(d, name)}
</div>
)
}
/**
* The Map's pages: `research/map`, and a project's at `research/map/<owner>/<name>`, with
* `/files/<path>` and `/settings` for its other tabs.
*/
export function mapView(d: TreeState | null, place: string): m.Children {
if (!state.graph) {
load()
return <p class="hint">{state.error || 'Reading every project…'}</p>
}
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()
}