import m, {MithrilComponent} from '@garage44/mithril' import {Button, Card, Dialog, Table, FieldNumber, FieldSelect, FieldSwitch, FieldTags, FieldText, FieldTextarea} from '@garage44/mithril/components' import {seg} from '@/components/autopilot' import {Bars, SERIES} from '@/components/charts' import {openTreeTalk, talkAboutTree} from '@/components/discuss' import {pipsView} from '@/components/pips' import {mapView} from '@/components/projectmap' import {askConfirm} from '@/components/confirm' import {act} from '@/lib/actions' import {api} from '@/lib/api' import type {Direction, DirectionNext, Goal, Insight, LiveLine, Round, Tech, TechState, TreeState} from '@/lib/api' import {age, ahead, dur, shortName} from '@/lib/format' import {hooks as talkHooks, talking} from '@/lib/discuss' import {askProjects, projectName, projectSelect, projects, shown} from '@/lib/projects' import {bind, local} from '@/lib/reactive' import {go, here} from '@/lib/route' import {$s, steers} from '@/lib/store' import {CARD_H, CARD_W, HEAD_H, LANE_HEAD, branches, curve, evidenceNames, frontier, goalsUnder, layout, leadsTo, lineOf, looksOf, moveTime, pathOf, pipOf, pips, progress, history, seenBy, techsOf, themes, wayOf} from '@/lib/tree' import type {Branch, Look, Run, Step} from '@/lib/tree' /** * The research tree (tree.rs, docs/mockups/research-tree): the person's goals * at the far end, the techs on the way with what each needs, read left to * right (on a phone, as indented branches). A scout fills it in, one round at a * time — Map (what is built), Harvest (what earlier sessions left open) and * Group (themes, proposed as goals under this one) — and what is not a tech yet * is an insight: on its tech as a caveat, or below the tree. A tech that is not * a guess can be built by hand, or all of a goal by itself (a direction). * Goals and their themes (the goals under one) are chosen in one bar above * the page (`goalBar`), the tree drawn under it in lanes by theme. The scout is * docked in the tree with one action, a look (`scoutBar`, tree.rs `look`), and * what a look brought glows on the tree until it is seen (docs/mockups/scout). */ // `focus` is the tech whose line is lit after a tap, `hover` the one under the pointer, which wins while it is there. // `notesBy` filters the notes by who wrote them, `openNote` is the one unfolded. const state = local({ data: null as TreeState | null, error: '', loading: false, goal: '', picked: '', focus: '', hover: '', dropWhy: '', dropping: false, idea: '', showDropped: false, allBuilt: false, notesBy: 'all' as 'all' | 'person' | 'scout', allNotes: false, openNote: '', // The goal's menu open; what to send the scout to look at; the tech whose popover is open and the question typed in it; // which of a look's finds is walked to (-1: none yet); the look whose finds the log lights; What next unfolded. menu: false, ask: '', pop: '', popAsk: '', walk: -1, lookShown: '', allLooks: false, nextOpen: false, notesOpen: false, historyOpen: false, headGoal: '', // The height the screen has for the tree, so a short tree is spread over it (`fill`). fill: 0, // When the open tech's dialog opened, so what was changed since shows old beside new; and whether a voice conversation opened it. pickedAt: 0, talkOpened: false, // The scout's details unfolded under its one line while it looks. scoutOpen: false, // The projects picked for a goal the scout cannot read yet (`scoutStart`), and that goal. startFor: '', startRepos: {} as Record, // A field's edit that Undo answered (`:` → that answer's time), so the undo itself shows as no change. undone: {} as Record, }) let timer: ReturnType | null = null /** When a pull of the tree (grab) last ended: the click that ends it is no tap on the background. */ let pulled = 0 /** Below the tree on the screen: the scout's log under it and the board's padding. */ const UNDER_TREE = 64 /** * The tree fills the screen down to its bottom edge: the window's height less where the tree starts, measured from * the top of what scrolls, so scrolling the page does not change it. Drawn again only when it moved. */ function measureFill(el: Element) { let top = el.getBoundingClientRect().top + window.scrollY let height = window.innerHeight for (let p = el.parentElement; p; p = p.parentElement) { const o = getComputedStyle(p).overflowY if (o === 'auto' || o === 'scroll') { top = el.getBoundingClientRect().top - p.getBoundingClientRect().top + p.scrollTop height = p.clientHeight break } } const fill = Math.max(0, Math.round(height - top - UNDER_TREE)) if (Math.abs(fill - state.fill) > 8) { state.fill = fill requestAnimationFrame(() => m.redraw()) } } const onResize = () => m.redraw() function load() { if (state.loading) return state.loading = true api.tree() .then((d) => { state.data = d state.error = '' }) .catch((e) => (state.error = (e as Error).message)) .finally(() => { state.loading = false // While a round goes on, look again now and then: its answer comes from a runner. if (timer) clearTimeout(timer) if (state.data?.rounds.some((r) => r.state === 'queued' || r.state === 'asked')) timer = setTimeout(load, 8000) // While the tree heads somewhere, its researches start and land on their own: look now and then. else if (directionsOf(state.data).some((x) => !x.reached)) timer = setTimeout(load, 30000) }) } // A voice conversation about the tree (discuss.ts) talks about the goal shown, and what it changes is drawn at once. talkHooks.treeGoal = () => (state.data ? (pickedGoal(state.data)?.id ?? '') : '') talkHooks.treeShow = (id) => { state.goal = id state.focus = '' } talkHooks.treeOpen = (id) => { pick(id) state.pop = '' state.talkOpened = true m.redraw() } talkHooks.treeChanged = (d) => { state.data = d // A round it sent out: looked at until it is back, as the page's own are. if (d.rounds.some((r) => r.state === 'queued' || r.state === 'asked')) load() } /** Fresh when the page is looked at again. */ export function reloadTree() { load() } /** A tech opened on the tree, from a session that researches it: its dialog, its line lit. */ export function showTech(id: string) { state.picked = id state.focus = id go('research') } async function treeOp(what: string, op: string, fields: Record, quiet = false): Promise { let out: TreeState | null = null await act(what, async () => { out = await api.treeOp(op, fields) state.data = out }, {quiet}) if (out && (out as TreeState).rounds.some((r) => r.state === 'queued' || r.state === 'asked')) load() return out } const STATE_WORD: Record = {built: 'built', researching: 'being built', available: 'available', locked: 'locked', fog: 'in the fog', dropped: 'not this'} /** A tech's dialog opens on where it stands, in a few words, and then a sentence: what is asked of you. */ const STATUS_TITLE: Record = { built: 'Built', researching: 'Being built now', available: 'Ready to start', locked: 'Waits on what it needs', fog: 'A guess of the scout', dropped: 'Not this', } function statusText(d: TreeState, t: Tech, link: (id: string) => m.Vnode): m.Children { const heading = headingFor(d, t.id) ? ' The tree heads this way: it starts by itself when its turn comes.' : '' switch (t.state) { case 'researching': return t.research ? ['Session ', link(t.research.session), ' is building it. What it needs from you, it asks there.'] : 'A session is building it. What it needs from you, it asks there.' case 'available': return `Everything it needs is built. Start building opens a session for it, which you steer as any other.${heading}` case 'locked': return `It can start once what it needs first is built. You can start building it now all the same.${heading}` case 'fog': return 'A guess: only one look found it. Start building it, or let it be: a second finding confirms it, and one nobody starts fades in a month.' case 'built': return 'It works on main: nothing is asked of you.' case 'dropped': if (t.faded) return 'A guess that faded: nobody started it and no look found it again in a month. A look that finds it brings it back.' return `${t.dropped?.why ? `Not this: ${t.dropped.why}. ` : ''}The scout will not bring it back.` } } /** What each state means, said beside it in the legend. */ const STATE_MEANS: Record = { built: 'works on main', researching: 'a session is building it now', available: 'all it needs is built: ready to start', locked: 'waits on something not built yet', fog: 'a guess of the scout: a second finding confirms it, and one nobody starts fades in a month', } const SIZE_WORD: Record = {S: 'about one session', M: 'two or three sessions', L: 'more: split before it is researched'} const SIZE_SHORT: Record = {S: 'small', M: 'medium', L: 'large'} /** How the scout came to a tech, in words: the moves' own names are the hub's, not the page's. */ const MOVE_WORD: Record = {map: 'reading the code', harvest: 'reading sessions that ended', group: 'sorting into themes', sketch: 'drawing it', person: 'you'} /** What is on record about a tech that is not faded: the scout's insights on it, and your own. */ function caveatsOf(d: TreeState, id: string): Insight[] { return d.insights.filter((i) => i.about === id && !i.faded) } /** “Keep” and “Not this” for a guess, right where it is listed: the one decision the fog waits on. */ function decide(t: Tech): m.Children { if (t.state !== 'fog') return null return ( ) } /** A session on a tech, its brief written by the hub from the tech, after a yes: it starts work, and costs a session. */ async function research(t: Tech) { const repo = t.repos[0]?.split('/').pop() ?? 'its goal’s project' const yes = await askConfirm({ title: `Start building “${t.name}”?`, text: (

A session starts in {repo}, its brief written from this tech: what it is, who notices, what exists, what it needs, the evidence and what is on record about it. You steer it as any other.

), yes: 'Start the session', }) if (yes) await treeOp('research started', 'research', {id: t.id}) } /** Whether a Sketch round for this tech, or for its goal as a whole, is going. */ function sketching(d: TreeState, t: Tech): boolean { return d.rounds.some((r) => r.move === 'sketch' && (r.state === 'queued' || r.state === 'asked') && t.goals.includes(r.goal)) } /** A Sketch round on one tech: its mockup drawn (again). */ async function sketch(d: TreeState, t: Tech) { const goal = t.goals.find((g) => d.goals.some((x) => x.id === g && x.repos.length)) ?? t.goals[0] if (goal) await treeOp('Sketch: asked', 'scout', {goal, move: 'sketch', tech: t.id}) } function pick(id: string) { if (state.picked !== id) { state.pickedAt = Date.now() / 1000 state.talkOpened = false } state.picked = id state.focus = id state.dropWhy = '' state.dropping = false } /** A tech's icon, as the hub rebuilt it; its first letter until it has one. */ function iconOf(t: {icon?: string | null; name: string}, cls = 'tree-icon'): m.Children { return t.icon ? {m.trust(t.icon)} : {t.name.slice(0, 1).toUpperCase()} } /** * Whether a goal is in the project shown (projects.tsx `shown`, the same choice as Sessions'): its projects, or those * of the goal it is under, name it. A goal that names none yet is in every view, so it is never lost to one. */ function goalInView(d: TreeState, g: Goal): boolean { const p = shown() if (!p) return true const r = repos_(d, g) return !r.length || r.includes(p) } function pickedGoal(d: TreeState): Goal | undefined { const want = state.goal || d.last_goal || '' const seen = d.goals.filter((g) => goalInView(d, g)) return seen.find((g) => g.id === want) ?? seen.find((g) => !g.parent) ?? seen[0] } /** The project picker on the Goals page, each project with how many goals of its own. */ function goalProjects(d: TreeState): m.Children { return projectSelect((repo) => d.goals.filter((g) => !g.parent && repos_(d, g).includes(repo)).length, "show one project's goals") } /** The goal at the top of `g`'s line: the one its themes are under. */ function rootOf(d: TreeState, g: Goal): Goal { let at = g for (let i = 0; i < 8 && at.parent; i++) { const up = d.goals.find((x) => x.id === at.parent) if (!up) break at = up } return at } /** The goal and its themes in the order the bar shows them, and ← → steps through: the goal first. */ function stops(d: TreeState, g: Goal): Goal[] { const root = rootOf(d, g) const th = themes([], d.goals, root.id).list return [root, ...th.map((x) => d.goals.find((y) => y.id === x.goal)).filter((x): x is Goal => !!x)] } function show(id: string) { state.goal = id state.focus = '' state.pop = '' state.walk = -1 state.lookShown = '' } /** * The one way between goals and themes, at the top of the page: the goal as a block (how far it is, and * a menu with the other goals and its tools), then its themes as tabs, each in its colour with how far * it is. A tab shows that theme alone; ← → steps through them. A theme with themes of its own opens a * second row. The tree's lanes wear the same colours. */ function goalBar(d: TreeState, g: Goal): m.Children { const root = rootOf(d, g) const tops = d.goals.filter((x) => !x.parent && x.id !== root.id && goalInView(d, x)) const p = progress(techsOf(d, root.id)) const all = p.known + p.fog const line: Goal[] = [] for (let at: Goal | undefined = g; at && line.length < 8; at = d.goals.find((x) => x.id === at!.parent)) line.unshift(at) const tab = (x: Goal, slot: number) => { const q = progress(techsOf(d, x.id)) const n = q.known + q.fog const on = line.some((y) => y.id === x.id) return ( ) } const rowOf = (parent: Goal) => themes([], d.goals, parent.id).list.map((x) => tab(d.goals.find((y) => y.id === x.goal)!, x.slot)) const deeper = line.slice(1).filter((x) => d.goals.some((y) => y.parent === x.id)) const item = (label: m.Children, onclick: () => void, off = false) => ( ) return ( ) } /** What a look brought, in a few words. */ function lookWord(l: Look): string { if (l.going) return 'looking…' const c = l.counts const parts = [ c.added ? `${c.added} new` : '', c.built ? `${c.built} built` : '', c.confirmed ? `${c.confirmed} confirmed` : '', c.themes ? `${c.themes} themes` : '', c.mockups ? `${c.mockups} sketches` : '', c.insights ? `${c.insights} notes` : '', ].filter(Boolean) if (!parts.length && l.failed) return 'failed' if (!parts.length && l.rounds.every((r) => r.state === 'stopped' || r.state === 'skipped')) return 'stopped' return parts.join(', ') || 'nothing new' } /** The scout's looks at this goal and the themes under it, oldest first. */ function looksFor(d: TreeState, g: Goal): Look[] { const under = goalsUnder(d.goals, g.id) return looksOf(d.rounds).filter((l) => under.includes(l.goal)) } /** Whether a look brought anything to show on the tree. */ function brought(l: Look): boolean { return Object.values(l.changed).some((x) => x.length > 0) } /** The look whose finds the tree lights: the one picked in the log, else the one going, else the last one back and not seen. */ function shownLook(d: TreeState, g: Goal): Look | null { const looks = looksFor(d, g) if (state.lookShown) return looks.find((l) => l.id === state.lookShown) ?? null const last = looks.at(-1) if (!last) return null return last.going || (!seenBy(last, $s.account) &&brought(last) && (last.ended ?? 0) > Date.now() / 1000 - 7 * 86400) ? last : null } /** A look's finds, one by one, as ‹ › walks them: what is new, what is now built, what it confirmed, drew, or noted. */ function findsOf(d: TreeState, l: Look): {kind: string; tech?: Tech; note?: Insight}[] { const tech = (id: string) => d.techs.find((t) => t.id === id) const out: {kind: string; tech?: Tech; note?: Insight}[] = [] const had = new Set() for (const [kind, ids] of [['new', l.changed.added], ['now built', l.changed.built], ['confirmed', l.changed.confirmed], ['sketched', l.changed.drawn]] as const) { for (const id of ids) { const t = tech(id) if (t && !had.has(id)) { had.add(id) out.push({kind, tech: t}) } } } for (const id of l.changed.insights) { const note = d.insights.find((i) => i.id === id && !i.faded) if (note) out.push({kind: 'note', note, tech: note.about ? tech(note.about) : undefined}) } return out } /** Walk to one of a look's finds: its line lit, its card in sight. */ function walkTo(d: TreeState, l: Look, i: number) { const finds = findsOf(d, l) if (!finds.length) return state.walk = (i + finds.length) % finds.length const t = finds[state.walk]!.tech state.focus = t?.id ?? '' state.pop = '' if (t) requestAnimationFrame(() => document.querySelector(`[data-tech="${t.id}"]`)?.scrollIntoView({block: 'nearest', inline: 'center', behavior: 'smooth'})) } /** One move of a look, as its bar says it. */ function stepWord(d: TreeState, r: Round, repos: string): string { const about = r.about ? d.techs.find((t) => t.id === r.about)?.name : '' switch (r.move) { case 'map': return about ? `Look at “${shortName(about, 28)}”` : `Read ${repos}` case 'harvest': return 'Read the sessions that ended' case 'group': return 'Sort into themes' case 'sketch': return about ? `Draw “${shortName(about, 24)}”` : 'Draw sketches' default: return r.move } } /** The scout at work on this goal or a theme under it: the look going, what it reads now, and the files it read. */ function scoutNow(d: TreeState, g: Goal): {look: Look; reading: string; read: string[]} | null { const look = looksFor(d, g).find((l) => l.going) if (!look) return null const lines = look.rounds.flatMap((r) => (r.live?.lines ?? []).filter((x) => x.kind === 'read')) const now = look.rounds.find((r) => r.state === 'asked')?.live?.lines.find((x) => x.kind === 'read') return {look, reading: now?.text ?? '', read: lines.map((x) => x.text)} } /** How many of the scout's steps the bar shows while it reads. */ const LIVE_SHOWN = 4 /** How much a move read, in words. */ function readCount(l: {reads: number; searches: number}): string { return [l.reads ? `${l.reads} ${l.reads === 1 ? 'file' : 'files'}` : '', l.searches ? `${l.searches} ${l.searches === 1 ? 'search' : 'searches'}` : ''].filter(Boolean).join(', ') } /** One step of the scout at work, as the bar says it. */ function liveWord(x: LiveLine): m.Children { switch (x.kind) { case 'read': return ['Reading ', {x.text}, ` in ${x.repo}`] case 'search': return ['Searching for “', {x.text}, `”${x.in ? ` in ${x.in}` : ''} in ${x.repo}`] default: return ['Listing ', {x.text}, ` in ${x.repo}`] } } /** About how long a look still takes, from how long its moves took before; none while one has no record. */ function timeLeft(d: TreeState, l: Look): string { const t0 = Date.now() / 1000 let left = 0 for (const r of l.rounds) { if (r.state !== 'queued' && r.state !== 'asked') continue const took = moveTime(d.rounds, r.move) if (took === null) return '' left += r.state === 'asked' && r.taken_at ? Math.max(30, took - (t0 - r.taken_at)) : took } const min = Math.round(left / 60) return left ? (min <= 1 ? 'about a minute left' : `about ${min} min left`) : '' } /** Send the scout: a look at a goal or theme, or at one tech with one of the page's questions. */ async function look(g: Goal, fields: Record = {}) { const out = await treeOp('the scout went to look', 'look', {goal: g.id, ...fields}) if (out) { state.lookShown = '' state.walk = -1 } return out } const SCOUT_ICON = ( ) /** * The scout, docked in the tree: one button, Research further, and a line for what to look at. While it * looks, its moves in words and Stop; when it is back, what it brought as counts and a walk through it on * the tree, until “Seen it”. Which moves a look makes the hub decides (tree.rs `look`). */ function scoutBar(d: TreeState, g: Goal): m.Children { const repos = repos_(d, g) if (!repos.length) return scoutStart(d, g) const names = repos.map((r) => r.split('/').pop()).join(', ') const looks = looksFor(d, g) // The look at work, and those asked meanwhile, each waiting for the one before it (tree.rs `look`). const [going, ...waiting] = looks.filter((l) => l.going) if (going) { const at = d.goals.find((x) => x.id === going.goal) const about = going.about ? d.techs.find((t) => t.id === going.about) : null // The question in the person's words: the focus less the page's own words for a question about one tech. const asked = (l: Look) => l.focus?.trim() ?? '' const now = going.rounds.find((r) => r.state === 'asked') const live = now?.live const moves = going.rounds.filter((r) => r.state !== 'skipped') const reading = live?.lines[0] // One line above the tree (docs/mockups/scout 6-scout-in-tree): the rest folds open under Details, over the tree. return (
{SCOUT_ICON} The scout is looking at {about ? `“${about.name}”` : `“${at?.name ?? g.name}”`} · {age(going.at)} You asked {asked(going) || 'what is built, what comes next, what earlier sessions left open'} `${stepWord(d, r, names)}: ${r.state === 'asked' ? 'now' : r.state}`).join(' · ')}> {moves.map((r) => ( ))} {reading ? [reading.kind === 'read' ? 'reading ' : 'searching ', {reading.kind === 'read' ? reading.text.split('/').slice(-2).join('/') : reading.text}] : now ? stepWord(d, now, names).toLowerCase() : 'waiting its turn'} {waiting.length ? +{waiting.length} after this : null}
{state.scoutOpen ? scoutDetails() : null}
) function scoutDetails(): m.Children { return (

You asked{going.via === 'talk' ? ' · in the conversation' : ''} {asked(going) || 'Research further: what is built, what comes next, what earlier sessions left open'}

{going.rounds.map((r) => ( {r.state === 'done' ? '✓ ' : r.state === 'failed' ? '✕ ' : null} {r.state === 'asked' ? : null} {stepWord(d, r, names)} {r.state === 'skipped' ? ': not needed' : null} {r.live && (r.live.reads || r.live.searches) ? · {readCount(r.live)} : null} ))} {timeLeft(d, going)} {live && (live.lines.length || live.thought) ? (
{live.lines.slice(0, LIVE_SHOWN).map((x, i) => (
{i === 0 ? 'now' : age(x.at)} {liveWord(x)}
))} {live.thought ? (
“{live.thought}” What it said last while reading: a guess until it is back
) : null}
) : now ? (

It has just started reading; what it reads shows here as it goes.

) : null}
After this {waiting.map((l) => ( {asked(l) || 'Research further'} {l.via === 'talk' ? · in the conversation : null} ))} {/* A question asked now waits for this look and goes by itself after it. */} {state.ask.trim() ? ( ) : null}
) } } const shown = shownLook(d, g) if (shown && !state.lookShown) { const finds = findsOf(d, shown) const c = shown.changed const at = finds[state.walk] const chip = (n: number, tone: string, word: string) => (n ? {n} {word} : null) const newOnes = c.added.filter((id) => !c.built.includes(id)).length return (
{SCOUT_ICON} The scout is back {age(shown.ended) === 'now' ? 'just now' : `${age(shown.ended)} ago`} {chip(newOnes, 'new', 'new')} {chip(c.built.length, 'built', 'now built')} {chip(c.confirmed.filter((id) => !c.added.includes(id)).length, 'confirmed', 'confirmed')} {chip(c.drawn.filter((id) => !c.added.includes(id)).length, 'drawn', 'sketched')} {chip(c.insights.length, 'note', c.insights.length === 1 ? 'note' : 'notes')} {finds.length ? ( {state.walk < 0 ? `${finds.length} to see` : `${state.walk + 1} of ${finds.length}`} ) : null}
{at ? (

{at.kind}: {at.note ? at.note.text : at.tech ? [, at.tech.what ? ` — ${at.tech.what}` : ''] : null}

) : null}
) } const last = looks.at(-1) return (
{SCOUT_ICON} The scout reads {names} and fills in the tree. {last ? `Last look ${age(last.ended ?? last.at)} ago: ${lookWord(last)}.` : 'It has not looked yet.'} {talkAboutTree() ? ( ) : null}
) } /** The workspace's projects as chips to pick, on in the scout's colour. */ function repoChips(on: Record, flip: (repo: string) => void): m.Children { return (
{projects.list.map((p) => ( ))}
) } /** * A goal the scout cannot read yet, because no project is named on it or above it: the projects are picked here, * in the tree, and the three steps say what follows (docs/mockups/scout 7-start). The pick goes on the goal at the * top, which `repos_` reads for its themes too. */ function scoutStart(d: TreeState, g: Goal): m.Children { askProjects() if (state.startFor !== g.id) { state.startFor = g.id // The project shown is the one it is about, until the person says otherwise. const one = shown() || (projects.list.length === 1 ? projects.list[0].repo : '') state.startRepos = one ? {[one]: true} : {} } const picked = projects.list.filter((p) => state.startRepos[p.repo]).map((p) => p.repo) const send = async () => { const top = rootOf(d, g) const saved = await treeOp('projects named', 'goal_save', { id: top.id, name: top.name, statement: top.statement, who: top.who, signs: top.signs, never: top.never, parent: top.parent, repos: picked, }, true) if (saved && (await look(g, {focus: state.ask.trim()}))) state.ask = '' } return (
{SCOUT_ICON} The scout doesn't know where to look yet
  1. Pick the project(s) this goal is about {repoChips(state.startRepos, (r) => (state.startRepos = {...state.startRepos, [r]: !state.startRepos[r]}))}
  2. Send the scout: it reads their code, without changing it, for a few minutes
  3. Cards appear on the tree: what is built, and what comes next
) } /** * The tree while the scout's first look is still out: the same three steps, two ticked or going, and * placeholders where its cards will land, so an empty tree reads as one being filled in. */ function firstLook(d: TreeState, g: Goal): m.Children { const now = scoutNow(d, g) if (!now) return null const names = repos_(d, g).map((r) => projectName(r)).join(', ') const reads = now.look.rounds.reduce((n, r) => ({reads: n.reads + (r.live?.reads ?? 0), searches: n.searches + (r.live?.searches ?? 0)}), {reads: 0, searches: 0}) const counted = readCount(reads) const left = timeLeft(d, now.look) return (
  1. Projects picked: {names}
  2. Reading the code{[counted, left].filter(Boolean).length ? ` — ${[counted, left].filter(Boolean).join(', ')}` : ''}
  3. Cards on the tree

The tree fills in here as the scout finds things. You can leave this page: it carries on.

) } /** The projects a goal is read in: its own, else those of the goal it is under (tree.rs `repos_of`). */ function repos_(d: TreeState, g: Goal): string[] { for (let at: Goal | undefined = g, i = 0; at && i < 8; at = d.goals.find((x) => x.id === at!.parent), i++) if (at.repos.length) return at.repos return [] } /** The scout's looks as a row of chips under the tree: a tap lights on the tree what that one brought. */ function lookLog(d: TreeState, g: Goal): m.Children { const looks = looksFor(d, g).filter((l) => !l.going).reverse() if (!looks.length) return null const list = state.allLooks ? looks : looks.slice(0, 4) const open = looks.find((l) => l.id === state.lookShown) const text = open?.rounds.map((r) => (r.state === 'failed' ? r.error : r.summary)).filter(Boolean).join(' ') return (
Scout's log {list.map((l) => ( ))} {looks.length > 4 ? ( ) : null}
{open ? (

{open.focus ? Looking at: {open.focus}. : null} {text || 'It said nothing more.'}

) : null}
) } /** The page's questions for the scout about one tech, each a look at that tech alone. */ const ASKS: {ask: string; word: string; when: (t: Tech) => boolean}[] = [ {ask: 'needs', word: 'What does it need first?', when: (t) => t.state !== 'built'}, {ask: 'smaller', word: 'Make it smaller', when: (t) => t.state !== 'built' && t.size !== 'S'}, {ask: 'draw', word: 'Draw how it looks', when: (t) => t.state !== 'built'}, {ask: 'exists', word: 'Is it built already?', when: (t) => t.state !== 'built'}, {ask: 'after', word: 'What comes after it?', when: () => true}, ] /** “Have the scout look further at this”: the questions as chips, and one in your own words. */ function askScout(d: TreeState, g: Goal, t: Tech): m.Children { const off = !steers() || !repos_(d, g).length const send = (ask: string, focus = '') => void look(g, {tech: t.id, ask, focus}).then((out) => { if (out) { state.popAsk = '' state.pop = '' } }) return (
Have the scout look further at this
{ASKS.filter((a) => a.when(t)).map((a) => ( ))}
{looksFor(d, g).some((l) => l.going) ? The scout is looking already: this waits for it and goes after it by itself. : null}
) } /** * Puts the popover on the screen by its card: under it, or over it when the window has no room below, kept * inside the window. Fixed to the window rather than the tree, which scrolls and would cut it off at its edge. */ function placePop(el: HTMLElement) { const card = document.querySelector(`.tree-canvas [data-tech="${CSS.escape(state.pop)}"]`) if (!card) return const r = card.getBoundingClientRect() const gap = 8 const w = el.offsetWidth const h = el.offsetHeight const below = r.bottom + gap + h <= window.innerHeight - gap || r.top - gap - h < gap el.style.left = `${Math.max(gap, Math.min(r.left, window.innerWidth - w - gap))}px` el.style.top = `${Math.max(gap, below ? r.bottom + gap : r.top - gap - h)}px` el.style.visibility = 'visible' } /** * A mouse pulls the wide tree around by its background, as a map: sideways the tree's scroller, up and down * what scrolls the page. Touch scrolls by itself, and a card, a button or the popover keeps its own click. */ function grab(e: PointerEvent) { if (e.pointerType !== 'mouse' || e.button !== 0 || (e.target as Element).closest('button, a, input, textarea')) return const box = e.currentTarget as HTMLElement let page = box.parentElement while (page && !['auto', 'scroll'].includes(getComputedStyle(page).overflowY)) page = page.parentElement const pane = page ?? (document.scrollingElement as HTMLElement) const x0 = e.clientX const y0 = e.clientY const left = box.scrollLeft const top = pane.scrollTop let moved = false const move = (ev: PointerEvent) => { const dx = ev.clientX - x0 const dy = ev.clientY - y0 if (!moved && Math.hypot(dx, dy) < 4) return moved = true box.classList.add('tree-scroll--pulled') box.scrollLeft = left - dx pane.scrollTop = top - dy } const up = () => { window.removeEventListener('pointermove', move) window.removeEventListener('pointerup', up) window.removeEventListener('pointercancel', up) box.classList.remove('tree-scroll--pulled') if (moved) pulled = performance.now() } window.addEventListener('pointermove', move) window.addEventListener('pointerup', up) window.addEventListener('pointercancel', up) // No text selected on the way. e.preventDefault() } /** A tapped tech on the wide tree: what it is, its one decision, and the scout's questions about it. */ function popover(d: TreeState, g: Goal, t: Tech): m.Children { return (
e.stopPropagation()} oncreate={(v: m.VnodeDOM) => { const el = v.dom as HTMLElement const follow = () => placePop(el) ;(el as HTMLElement & {follow?: () => void}).follow = follow // Any scroll, the tree's or the page's, moves the card: the popover goes with it. window.addEventListener('scroll', follow, true) window.addEventListener('resize', follow) follow() }} onupdate={(v: m.VnodeDOM) => placePop(v.dom as HTMLElement)} onremove={(v: m.VnodeDOM) => { const follow = (v.dom as HTMLElement & {follow?: () => void}).follow if (!follow) return window.removeEventListener('scroll', follow, true) window.removeEventListener('resize', follow) }} >
{iconOf(t)} {t.name} {STATE_WORD[t.state]} {t.state === 'built' ? '' : ` · ${t.size}`}
{t.what ?

{t.what}

: null}
{decide(t)} {t.state === 'available' || t.state === 'locked' ? ( ) : null} {t.state === 'researching' && t.research ? ( ) : null}
{askScout(d, g, t)}
) } /** One line of “What next”: an icon, what it is, and its buttons. */ function moveLine(kind: string, icon: m.Children, title: m.Children, sub: m.Children, tools: m.Children): m.Children { return (
{icon} {title} {sub ? {sub} : null} {tools}
) } /** A tech being built: "now" while it just started, how long it has been at it after. */ function nowTag(t: Tech): string { const a = age(t.research?.at) return a === 'now' || a === '–' ? 'now' : `now · ${a}` } /** * What can be built for this goal, and when, read top to bottom: what waits on you, what is being * built now, what can start now, and what comes later and after what. When nothing known is left, the * scout is the way on. The direction while it runs is drawn above, as its own way. */ function whatNext(d: TreeState, g: Goal, techs: Tech[]): m.Children { // Nothing on the tree: the scout's block in it is the one way on, and a second card saying so only repeats it. if (!techs.length) return null const dir = directionOf(d, g) const ids = new Set(techs.map((t) => t.id)) const byId = (id: string) => d.techs.find((t) => t.id === id) const of = themes(techs, d.goals, colourGoal(d, g)).of const nextId = dir && !dir.reached && !dir.paused ? (dir.next?.tech ?? '') : '' const heading = !!dir && !dir.reached && (dir.target === g.id || pathOf(d, dir.target).size > 0 && [...pathOf(d, dir.target)].some((id) => ids.has(id))) const sections: m.Children[] = [] const section = (title: string, sub: string, lines: m.Children[]) => { if (lines.length) sections.push(

{title} {sub ? {sub} : null}

{lines}
, ) } const name = (t: Tech) => ( ) const icon = (t: Tech) => {iconOf(t)} // What waits on you: the one thing nothing else moves without. const yours: m.Children[] = [] if (dir?.reached && (dir.target === g.id || ids.has(dir.target))) { const landed = dir.runs.filter((r) => r.outcome === 'landed').length yours.push( moveLine('done', CHECK, `Reached: ${dir.name}`, `${dir.runs.length} ${dir.runs.length === 1 ? 'session' : 'sessions'}, ${landed} landed · ${age(dir.reached)} ago`, ( )), ) } if (!repos_(d, g).length) { yours.push( moveLine('ask', GOAL_FLAG, 'Say which projects this goal is about', 'The scout reads only those.', ( )), ) } for (const t of techs.filter((x) => x.state === 'fog')) { yours.push(moveLine('fog', icon(t), name(t), `A guess of the scout: keep it and it can be built${t.mockup_png || t.mockup ? ' · sketched' : ''} · ${SIZE_SHORT[t.size] ?? t.size}`, decide(t))) } for (const p of (d.proposals ?? []).filter((x) => x.goal === g.id)) { const names = p.techs.map((id) => byId(id)?.name).filter((n): n is string => !!n) yours.push( moveLine('theme', , `Theme: ${p.name}`, p.statement || `${names.length} techs: ${names.slice(0, 3).join(', ')}${names.length > 3 ? ` and ${names.length - 3} more` : ''}`, ( )), ) } section('Waits on you', '', yours) // The way: what is left, numbered in the order it is built (tree.ts `wayOf`, as the hub starts them). // A guess waits on you first, above; it joins the way once kept. const way = wayOf(techs.filter((t) => t.state !== 'fog')) const ready = way.filter((x) => x.tech.state === 'available') const later = way.filter((x) => x.tech.state === 'locked') const stepLine = ({tech: t, n, after}: Step) => { const now = t.state === 'researching' const sub = now ? t.research ? `being built in session ${t.research.session} · started ${age(t.research.at) === 'now' ? 'just now' : `${age(t.research.at)} ago`}` : 'being built' : after.length ? `after step ${after.join(', ')} · ${SIZE_SHORT[t.size] ?? t.size}` : `can start now · ${SIZE_WORD[t.size] ?? t.size}${t.id === nextId && dir?.next ? ` · starts by itself: ${nextWord(d, dir.next)}` : ''}` const tools = now ? [ {nowTag(t)}, t.research ? ( ) : null, ] : t.state === 'available' ? [ t.id === nextId ? next : null, , ] : t.id === nextId ? next : null return (
{now ? '▶' : n} {moveLine(now ? 'now' : after.length ? 'later' : 'ready', icon(t), name(t), sub, tools)}
) } section('The way', heading ? 'in this order, by itself, one at a time' : 'in the order it would be built', way.map(stepLine)) // All of it by itself, when more than one is left and the tree does not head here yet. const toBuild = ready.length + later.length const head = toBuild && g.repos.length && !heading ? (
{toBuild} still to build for this goal{ready.length ? `, ${ready.length} can start now` : ''}. Midas can build them one after another by itself, on autopilot.
) : null const empty = !techs.some((t) => t.state !== 'built' && t.state !== 'dropped') // Folded, it is one line of counts: the tree above says the rest, and a guess is decided on its card. const now = way.filter((x) => x.tech.state === 'researching').length const summary = [ yours.length ? `${yours.length} ${yours.length === 1 ? 'waits' : 'wait'} on you` : '', now ? `${now} being built` : '', ready.length ? `${ready.length} can start now` : '', later.length ? `${later.length} later` : '', ].filter(Boolean).join(' · ') const open = state.nextOpen && !empty return (
What next {empty ? 'Everything known is built: Research further, above, finds what comes next.' : summary || 'Nothing waits on you.'} {!open && head ? ( ) : null} {empty ? null : ( )}
{open ? [head, sections] : null}
) } /** Built by work, and found built already by a look: only the first is the week's work. */ const SERIES_BUILT = [ {label: 'built by a session', color: SERIES[0]!}, {label: 'found built by the scout', color: SERIES[1]!}, ] /** Each outcome in a word, for the sessions' table. */ const OUTCOME: Record = {landed: 'landed', dropped: 'dropped', done: 'done, not landed', ended: 'stopped'} /** * How the goal's work went, folded to one line: techs built a week, how many research sessions landed, * how long one takes and what they cost; open, the sessions themselves (lib/tree.ts `history`). */ function historyCard(techs: Tech[]): m.Children { const WEEKS = 8 const t0 = Date.now() / 1000 const x = history(techs, t0, WEEKS) if (!x.runs.length && !x.built.some(Boolean)) return null const month = x.built.slice(-4).reduce((s, n) => s + n, 0) const dollars = (v: number) => `$${v.toFixed(v < 10 ? 2 : 0)}` const summary = [ `${month} built in 4 weeks`, x.ended ? `${x.landed} of ${x.ended} sessions landed` : '', x.hours != null ? `about ${dur(x.hours * 3600)} each` : '', x.costed ? `${dollars(x.cost)} in all` : '', ].filter(Boolean).join(' · ') const open = state.historyOpen const weekOf = (i: number) => { const start = new Date((t0 - (WEEKS - i) * 7 * 86400) * 1000) return i === WEEKS - 1 ? 'this week' : `week of ${start.toLocaleDateString(undefined, {day: 'numeric', month: 'short'})}` } return (
How it went {summary}
{open ? [

Techs built a week

, i)} series={SERIES_BUILT} value={(i) => [x.built[i]!, x.found[i]!]} format={(v) => String(Math.round(v))} label={weekOf} />, x.runs.length ? ( r.id} rows={x.runs} columns={[ {key: 'tech', label: 'tech', cell: (r: Run) => { e.preventDefault(); pick(r.tech.id) }}>{shortName(r.tech.name, 40)}}, {key: 'at', label: 'started', cell: (r: Run) => (r.at ? `${age(r.at)} ago` : '–')}, {key: 'took', label: 'took', align: 'end', cell: (r: Run) => (r.ended && r.at ? dur(r.ended - r.at) : r.outcome ? '–' : 'at work')}, {key: 'outcome', label: 'how', cell: (r: Run) => (r.outcome ? (OUTCOME[r.outcome] ?? r.outcome) : 'at work')}, {key: 'cost', label: 'cost', align: 'end', cell: (r: Run) => (r.cost != null ? dollars(r.cost) : '–')}, {key: 'id', label: 'session', cell: (r: Run) => { e.preventDefault(); go(`sessions/${r.id}`) }}>{r.id}}, ]} /> ) : null, ] : null} ) } /** To Directions, from the goal bar: how many go. */ function directionsLink(d: TreeState): m.Children { const n = directionsOf(d).length return [ , , ] } /** * Directions (docs/screens/directions.html): every direction going, over every project, in the person's * order, under one budget for all of them. ↑ ↓ move one; when the budget is short the first starts first, * and directions that reach one project take turns there (tree.rs `directions_step`). */ function directionsPage(d: TreeState): m.Children { const list = directionsOf(d) const b = d.budget ?? {at_once: 3, per_day: 10, per_project: 1, going: 0, today: 0, week_cost: 0} const move = (i: number, by: number) => () => { const ids = list.map((x) => x.id) ;[ids[i], ids[i + by]] = [ids[i + by]!, ids[i]!] void treeOp('order saved', 'direction_order', {ids}) } // A goal at the top of its line, not headed for yet: a theme is reached from its goal's tree. const free = d.goals.filter((g) => !g.parent && !headingFor(d, g.id) && g.repos.length) return (
Directions {list.length ? `${list.length} going, over every project` : 'none going'}
Across all directions
at most {b.at_once} at once · {b.per_day} started a day · {b.per_project === 1 ? 'one session' : `${b.per_project} sessions`} per project at a time
{Array.from({length: b.at_once}, (_, i) => ( ))} {b.going} of {b.at_once} at work · {b.today} of {b.per_day} today{b.week_cost ? ` · $${b.week_cost.toFixed(0)} this week` : ''}
{list.map((x, i) => directionCard(d, x, {up: i > 0 ? move(i, -1) : undefined, down: i < list.length - 1 ? move(i, 1) : undefined}))} {list.length ? null :

Nothing is researched by itself. Head for a goal: its techs are then built one after another, on autopilot.

} {free.length ? (
({value: g.id, label: g.name}))} />
) : null} {formDialog()}
) } /** The directions going (until stopped), in the person's order. */ function directionsOf(d: TreeState | null): Direction[] { return (d?.directions ?? []).filter((x) => !x.cleared) } /** * The direction a goal's page shows: the first going whose target is this goal, a goal under it or one of its * techs; else, with none given, the first going. Several can go at once (Directions shows them all). */ function directionOf(d: TreeState, g?: Goal | null): Direction | null { const going = directionsOf(d) if (!g) return going[0] ?? null const under = new Set(goalsUnder(d.goals, g.id)) const ofGoal = (target: string) => under.has(target) || d.techs.some((t) => t.id === target && t.goals.some((x) => under.has(x))) return going.find((x) => ofGoal(x.target)) ?? null } /** The direction heading for a goal or tech already, if one is. */ function headingFor(d: TreeState, id: string): Direction | null { return directionsOf(d).find((x) => x.target === id) ?? null } interface Limits { at_once: number per_day: number scout: boolean scout_every: number } /** A direction's limits as they stand, or the hub's defaults (tree.rs `DIRECTION_*`). */ function limitsOf(dir: Direction | null): Limits { return {at_once: dir?.at_once ?? 1, per_day: dir?.per_day ?? 4, scout: dir?.scout ?? true, scout_every: dir?.scout_every ?? 3} } /** The limits of the direction going, in one line. */ function limitsLine(dir: Direction): string { const l = limitsOf(dir) const scout = !l.scout ? 'no scout' : l.scout_every ? `scout when the way runs out and every ${l.scout_every} landings` : 'scout when the way runs out' return `${l.at_once} at once · ${l.per_day} a day · ${scout}` } /** * The page's one small form at a time, in a dialog of its own (the shared confirm keeps its text in reactive * state, where a form's fields do not survive): heading for a goal or a tech with the direction's limits, the * limits of the direction going, or when a tech is done. */ const form = local({ open: '' as '' | 'head' | 'limits' | 'done' | 'budget', target: '', name: '', replaces: '', at_once: 1, per_day: 4, scout: true, scout_every: 3, done: '', b_at_once: 3, b_per_day: 10, b_per_project: 1, }) /** What to do once the form is sent (the tech's dialog closes): never in `form`, as reactive state calls a function put in it. */ let afterForm: null | (() => void) = null /** Head for a goal or a tech: from then on the techs on the way are researched one after another, on autopilot. */ function headFor(d: TreeState, id: string, name: string, after?: () => void) { // One heading there already has its limits changed; a new one starts from the hub's defaults. const there = headingFor(d, id) const others = directionsOf(d).filter((x) => x !== there).length Object.assign(form, limitsOf(there), {open: 'head', target: id, name, replaces: there ? 'there' : others ? String(others) : ''}) afterForm = after ?? null } /** The direction's limits changed in place: what it started goes on. */ function changeLimits(dir: Direction) { Object.assign(form, limitsOf(dir), {open: 'limits', target: dir.id, name: dir.name}) afterForm = null } /** What every direction together may start. */ function changeBudget(d: TreeState) { const b = d.budget Object.assign(form, {open: 'budget', b_at_once: b?.at_once ?? 3, b_per_day: b?.per_day ?? 10, b_per_project: b?.per_project ?? 1}) afterForm = null } /** When a tech is done, in the person's words: the checks its session gives evidence for before it lands. */ function editDone(t: Tech) { Object.assign(form, {open: 'done', target: t.id, name: t.name, done: t.done ?? ''}) afterForm = null } async function submitForm() { const limits = {at_once: form.at_once, per_day: form.per_day, scout: form.scout, scout_every: form.scout_every} const {open, target, name, done} = form const after = afterForm afterForm = null form.open = '' if (open === 'head') await treeOp(`heading for ${name}`, 'direction_set', {target, ...limits}) if (open === 'limits') await treeOp('limits saved', 'direction_limits', {id: target, ...limits}) if (open === 'budget') await treeOp('budget saved', 'budget_set', {at_once: form.b_at_once, per_day: form.b_per_day, per_project: form.b_per_project}) if (open === 'done') await treeOp('saved', 'tech_edit', {id: target, done}) after?.() } function formDialog(): m.Children { const open = { get value() { return !!form.open }, set value(v: boolean) { if (!v) form.open = '' }, } const title = {'': '', head: `Head for “${form.name}”?`, limits: `How it heads for “${form.name}”`, done: `When is “${form.name}” done?`, budget: 'What all directions may start together'}[form.open] const yes = form.open === 'head' ? 'Head this way' : 'Save' const limits = [
, , , ] return ( (form.open = '')}> Cancel , , ]} >
{form.open === 'head' ? (

Midas then researches the techs on the way to it by itself, one after another: each a session on autopilot, landed when it is done, the tech built once it is on main. A guess on the way is kept when its turn comes. It pauses after two that land nothing; you can pause or stop it at any time. {form.replaces === 'there' ? ' It heads there already: this changes its limits.' : form.replaces ? ` It goes beside the ${form.replaces === '1' ? 'direction' : `${form.replaces} directions`} going, within the budget on Directions.` : ''}

) : null} {form.open === 'head' || form.open === 'limits' ? limits : null} {form.open === 'budget' ? [
, ,

Each direction keeps its own limits within these. When they are used up, the direction highest in the list starts next.

, ] : null} {form.open === 'done' ? ( ) : null}
) } /** A tech's sessions as pips: what landed, what is at work, what its size still expects. */ function techPips(t: Tech): m.Vnode | null { return pipsView(pips((t.sessions ?? []).map((s) => pipOf(s.outcome)), t.size, t.state === 'built')) } /** When the direction's next tech starts, in a few words (tree.rs `next_of`). */ function nextWord(d: TreeState, n: DirectionNext): string { const name = (id?: string | null) => shortName(d.techs.find((t) => t.id === id)?.name ?? 'what it needs', 24) switch (n.why) { case 'soon': return 'starting' case 'after': case 'at_once': return `after ${name(n.after)}` case 'per_day': return n.at ? ahead(n.at) : 'tomorrow' case 'focus': return 'when you have room' case 'paused': return 'paused' case 'scouting': return 'after the scout’s look' case 'budget': return 'when the budget has room' case 'project': return `when ${projectName(n.project ?? '') ?? n.project} is free` } } /** The session researching a tech now, opened from where it is named. */ function openResearch(t: Tech) { if (t.research) go(`sessions/${t.research.session}`) } /** * Where the tree is heading, as a line of stops: the tech landed last, what is at work now and for how * long, what starts next and when, and the goal. A stop opens its tech; the one at work its session. * On Directions, `order` moves it up or down the list, and each stop says which project it works in. */ function directionCard(d: TreeState, dir: Direction | null, order?: {up?: () => void; down?: () => void}): m.Children { if (!dir) return null const way = pathOf(d, dir.target) const on = d.techs.filter((t) => way.has(t.id)) const built = on.filter((t) => t.state === 'built').length const going = on.filter((t) => t.state === 'researching') const byId = (id?: string | null) => d.techs.find((t) => t.id === id) // The last tech a landing built: a landed session of a tech still at work is not a stop of its own. const lastLanded = byId(dir.runs.findLast((r) => r.outcome === 'landed' && byId(r.tech)?.state === 'built')?.tech) const next = dir.next && !going.some((t) => t.id === dir.next!.tech) ? byId(dir.next.tech) : undefined const share = on.length ? built / on.length : 0 // Which project each stop works in, once there is more than one to tell apart. const where = (p?: string | null) => (order && p ? {projectName(p) ?? p} : null) const repoOf = (t: Tech) => dir.runs.findLast((r) => r.tech === t.id)?.repo ?? t.lands_in?.find((r) => !t.landed_in?.includes(r)) ?? t.repos[0] const projects = [...new Set(on.flatMap((t) => (t.lands_in?.length ? t.lands_in : t.repos)))] const stop = (kind: string, t: Tech, sub: m.Children, onclick: () => void) => ( ) return (
{GOAL_FLAG} {dir.name} {built} / {on.length} {order ? ( ) : null} {order ? ( ) : null} {dir.reached ? null : ( )} {dir.reached ? null : ( )}
{lastLanded ? stop('done', lastLanded, techPips(lastLanded), () => pick(lastLanded.id)) : null} {going.map((t) => stop( 'now', t, [{nowTag(t)}, techPips(t), where(repoOf(t))], () => openResearch(t), ), )} {dir.next?.why === 'scouting' ? (
{SCOUT_MARK} The scout looks ahead {dir.scouted?.why === 'every' ? `after ${dir.scout_every} landings` : 'the way ran out'} · nothing starts meanwhile
) : null} {next && dir.next ? stop('next', next, [next, nextWord(d, dir.next), where(dir.next.project)], () => pick(next.id)) : null}
{GOAL_FLAG} {dir.reached ? 'Reached' : 'The goal'} {dir.reached ? null : `${on.length - built} to go`}
{dir.paused ? {dir.paused} : null} {dir.reached ? null : ( {order && projects.length ? `${projects.map((p) => projectName(p) ?? p).join(', ')} · ` : ''} {limitsLine(dir)} )}
) } const SCOUT_MARK = ( ) const CHECK = ( ) const GOAL_FLAG = ( ) /** * The goal whose themes colour the tree: this one when it has themes, else the one it is a theme of, so * a theme's cards wear the colour of its chip above the page (goalNav) rather than one per branch. */ function colourGoal(d: TreeState, g: Goal | undefined): string { if (!g) return '' return d.goals.some((x) => x.parent === g.id) ? g.id : (g.parent ?? g.id) } /** The class that gives a tech its branch's colour (`--theme`, app.css). */ function themeClass(of: Map, id: string): string { const slot = of.get(id) ?? -1 return `tree-theme-${slot < 0 ? 'none' : slot}` } /** One tech of the phone's tree, and what builds on it indented under it. */ function branchRow(b: Branch, x: Drawn): m.Children { const {lit, focus, of} = x const t = b.tech const caveats = caveatsOf(x.d, t.id).length return (
  • {decide(t)} {b.children.length ?
      {b.children.map((c) => branchRow(c, x))}
    : null}
  • ) } /** What a drawing of the tree shares: the lit line, the focused tech, each tech's theme. */ interface Drawn { d: TreeState lit: Set | null focus: string of: Map /** The tech the direction starts next. */ next: string /** What the scout's last look brought, still glowing. */ fresh: Set } function caveatWord(n: number): string { return n === 1 ? '1 caveat on record' : `${n} caveats on record` } function treeView(d: TreeState, g: Goal, all: Tech[]): m.Children { // What is open and what it stands on, unless asked for the whole past: on a grown tree most of it is built. const open = all.some((t) => t.state !== 'built') const techs = open && !state.allBuilt ? frontier(all) : all const hidden = all.length - techs.length if (!techs.length) { return (
    {scoutBar(d, g)} {/* Without a project the scout's block says what to do; while it looks, its first look shows. */} {!repos_(d, g).length ? null : scoutNow(d, g) ? firstLook(d, g) :

    Nothing on the tree yet: Research further fills it in.

    } {lookLog(d, g)}
    ) } const th = themes(all, d.goals, colourGoal(d, g)) // In lanes, one per theme, while the goal has themes; a branch of the tree is no theme to lay out by. const laned = th.list.some((x) => x.goal) const l = layout(techs, laned ? (t) => th.band.get(t.id) ?? -1 : undefined, state.fill) const focus = [state.hover, state.focus].find((id) => id && techs.some((t) => t.id === id)) ?? '' // Nothing tapped: the way the tree is heading, lit. const dir = directionOf(d, g) const lit = focus ? lineOf(techs, focus) : dir && !dir.reached ? pathOf(d, dir.target) : null const nextId = dir && !dir.reached ? (dir.next?.tech ?? '') : '' const counts = (s: TechState) => all.filter((t) => t.state === s).length const edgeLit = (a: string, b: string) => !!lit && lit.has(a) && (b === 'goal' || lit.has(b)) // What the scout's look brought glows until it is seen: new and confirmed, and what it found built. const shown = shownLook(d, g) const fresh = new Set([...(shown?.changed.added ?? []), ...(shown?.changed.confirmed ?? [])]) const nowBuilt = new Set(shown?.changed.built ?? []) // The scout in the tree while it looks: its theme's lane, the card whose code it reads now, the cards it read. const scout = scoutNow(d, g) const reading = scout?.reading ? techs.find((t) => evidenceNames(t, scout.reading))?.id ?? '' : '' const wasRead = new Set(scout ? techs.filter((t) => t.id !== reading && scout.read.some((f) => evidenceNames(t, f))).map((t) => t.id) : []) const drawn: Drawn = {d, lit, focus, of: th.of, next: nextId, fresh} // A look asked while one goes waits behind it (tree.rs `look`): only who may steer, and a goal with projects, matter. const busy = !steers() || !repos_(d, g).length const laneName = (b: number) => th.list[b]?.name ?? 'In no theme' // A tapped card's popover, over the whole screen rather than in the tree (placePop). const popAt = l.cards.find((c) => c.tech.id === state.pop) return (
    {/* Themes are chosen above the page (goalNav); here a colour only says which branch a card is on. */}
    The tree {/* Counts only: what a state means is its tooltip. */} {(['built', 'researching', 'available', 'locked', 'fog'] as TechState[]).filter((s) => counts(s)).map((s) => ( {counts(s)} {s === 'fog' ? (counts(s) === 1 ? 'guess' : 'guesses') : STATE_WORD[s]} ))} {open && (hidden || state.allBuilt) ? ( ) : null}
    {scoutBar(d, g)}
      {branches(techs).map((b) => branchRow(b, drawn))}
    {GOAL_FLAG} All of it leads to {g.name}
    measureFill(v.dom)} onupdate={(v: m.VnodeDOM) => measureFill(v.dom)} onpointerdown={grab} >
    { if (e.target === e.currentTarget && performance.now() - pulled > 300) { state.focus = '' state.pop = '' } }} > {l.lanes.map((x) => { const theme = th.list[x.band] return (
    {theme?.goal ? ( ) : ( {laneName(x.band)} )}
    ) })} {l.cols.map((x, i) => (
    {i === 0 ? 'Needs nothing' : `Step ${i + 1}`}
    ))}
    The goal
    {l.cards.map((c) => ( ))}
    {GOAL_FLAG} {g.name} {g.parent ? ( ) : ( everything on the tree leads here )}
    {l.ghosts.map((x) => { const theme = laned ? th.list[x.band] : undefined const target = theme?.goal ? d.goals.find((y) => y.id === theme.goal) : g return ( ) })}
    {popAt ? popover(d, g, popAt.tech) : null} {lookLog(d, g)}
    ) } function techDialog(d: TreeState): m.Children { const t = d.techs.find((x) => x.id === state.picked) const open = { get value() { return !!t }, set value(v: boolean) { if (!v) { state.picked = '' state.dropping = false } }, } if (!t) return const close = () => (state.picked = '') const caveats = caveatsOf(d, t.id) const needs = t.needs.map((id) => d.techs.find((x) => x.id === id)).filter((x): x is Tech => !!x) const next = leadsTo(d.techs, t.id).filter((x) => x.state !== 'dropped') const going = t.state !== 'built' && t.state !== 'dropped' const earlier = (t.sessions ?? []).filter((s) => s.id !== t.research?.session) const goal = d.goals.find((g) => t.goals.includes(g.id)) // A step on the way: what it needs, itself, what it leads to; each a tap away. const node = (x: Tech) => ( ) const sessionLink = (id: string) => ( { e.preventDefault() close() go(`sessions/${id}`) }}> {id} ) // In a voice conversation drawing it again is said, not pressed: the conversation sends the scout (discuss.ts). const remarks = t.remarks ?? [] const drawButton = !going ? null : sketching(d, t) ? ( The scout is drawing it{remarks.length ? '' : '…'} ) : talking() ? null : ( ) // A field changed since the dialog opened: what it was, struck through, beside what it is, and Undo. const field = (k: 'name' | 'what' | 'who' | 'differently' | 'exists' | 'done', now: string): m.Children => { const e = t.edited?.[k] if (!e || e.at < state.pickedAt || state.undone[`${t.id}:${k}`] === e.at) return now return [ e.was ? {e.was} : null, e.was ? ' ' : null, {now}, , ] } // The person's remarks on the mockup, for its next drawing. const remarkList = remarks.length ? (
      {remarks.map((r) => (
    1. {r.text}
    2. ))}
    ) : null // Pictures of the real thing, kept by a session in its project; a built tech without them can be photographed. const shots = t.shots ?? [] const waiting = (d.photos?.queue ?? []).indexOf(t.id) const photoNote = t.photographing && t.photograph ? ( Session {sessionLink(t.photograph.session)} is photographing it… ) : waiting >= 0 ? ( Waiting its turn to be photographed{waiting ? ` · ${waiting} before it` : ''} ) : t.state === 'built' ? ( ) : null const real = shots.length ? (
    {shots.map((s) => { const src = `/v1/hosted/tree/shots/${t.id}/${s.n}` return (
    {s.caption
    {s.caption ? {s.caption} : null}
    ) })}
    {t.state === 'built' ? 'As it works now' : 'As its session built it, before it landed'} {photoNote}
    ) : t.state === 'built' ? (
    No pictures yet of how it works. {photoNote}
    ) : null // The scout's photographed screen in the product's own look (a Sketch), where there are no pictures of the real thing; an older line drawing until it has one. const shot = t.mockup_png ? `/v1/hosted/tree/mockups/${t.id}?v=${t.mockup_png}` : '' const picture = real ? null : shot ? (
    {`Mockup:
    Where someone would use it · what is new is marked NEW {drawButton}
    {remarkList}
    ) : t.mockup ? (
    {m.trust(t.mockup)}
    Where someone would use it new already there {drawButton}
    {remarkList}
    ) : going ? (
    No mockup yet of where someone would use it. {drawButton}
    ) : null // A wide screen's sketch goes under the text, a phone's beside it. const wide = shot ? t.mockup_frame === 'wide' : !!t.mockup?.includes('viewBox="0 0 640 400"') const buttons: m.Vnode[] = [] if (state.dropping) { buttons.push( , , ) } else { // No "Not this" or "It is built" to decide: a tech is built when its session lands or the scout finds it on // main, and a guess nobody starts fades by itself (tree.rs `guess_faded`). Saying so in a conversation still can. if (going && !headingFor(d, t.id)) { buttons.push( , ) } // Starting a guess keeps it (tree.rs `mark_research`). if (t.state === 'available' || t.state === 'locked' || t.state === 'fog') { buttons.push( , ) } if (t.state === 'dropped') { buttons.push( , ) } } const title = ( {iconOf(t, 'tree-icon tree-icon--big')} {field('name', t.name)} ) return (
    {state.talkOpened && talking() ? (

    Opened in the conversation: what you say about it changes it here

    ) : null} {t.what ?

    {field('what', t.what)}

    : null} {/* The real thing comes first, right under what it is: what it looks like is the description. */} {real}
    {STATUS_TITLE[t.state]}

    {statusText(d, t, sessionLink)}

    {t.sessions?.length || !t.built ? (

    {techPips(t)} {t.built ? null : {SIZE_WORD[t.size]}} {/* The session at work is named in the sentence above; here the ones before it. */} {earlier.length ? sessions {earlier.map((s) => sessionLink(s.id))} : null}

    ) : null}
    {t.who || t.differently || (t.exists && !t.built) ? (

    What changes

    {t.who ? [
    For whom
    ,
    {field('who', t.who)}
    ] : null} {t.differently ? [
    What they do
    ,
    {field('differently', t.differently)}
    ] : null} {t.exists && !t.built ? [
    Already there
    ,
    {field('exists', t.exists)}
    ] : null}
    ) : null} {t.built ? null : (

    Done when

    {t.done ? field('done', t.done) : Not said yet: the session that builds it says it before it asks to land.}{' '}

    )}

    Where it sits

    {needs.length ? needs.map(node) :
    Needs nothing first: it can stand on its own
    }
    ↓
    {iconOf(t)} {t.name}
    ↓
    {next.length ? next.map(node) :
    {goal ? `Leads to the goal itself: ${goal.name}` : 'Leads to the goal itself'}
    }
    {caveats.length ? (

    On record about it{t.built ? ': built, but' : ''}

    {caveats.map((i) => (
    {i.text}
    {i.evidence.length ?
    {i.evidence.slice(0, 2).join(' · ')}
    : null}
    ))}
    ) : null}
    {picture}
    {pickedGoal(d) && t.state !== 'dropped' ? askScout(d, pickedGoal(d)!, t) : null}
    How the scout found it · by {t.moves.map((mv) => MOVE_WORD[mv] ?? mv).join(' and ')}, in {t.repos.map((r) => r.split('/').pop()).join(', ') || 'no project'} {t.evidence.length ? ` · ${t.evidence.length} ${t.evidence.length === 1 ? 'piece' : 'pieces'} of evidence` : ''} {t.evidence.length ? (
      {t.evidence.map((e) => (
    • {e}
    • ))}
    ) : (

    No evidence on record.

    )}
    {state.dropping ? (
    (v.dom as HTMLElement).querySelector('input')?.focus()}> The scout will not bring it back.
    ) : null}
    ) } function notesCard(d: TreeState, g: Goal): m.Children { // One about a tech stands on that tech (⚑), in its dialog: here only what is about the goal as a whole. const onTech = (i: Insight) => !!i.about && d.techs.some((t) => t.id === i.about) const mine = d.insights.filter((i) => i.goal === g.id && !i.faded) const live = mine.filter((i) => !onTech(i)).reverse() const elsewhere = mine.length - live.length const yours = live.filter((i) => i.move === 'person') const shown = state.notesBy === 'all' ? live : state.notesBy === 'person' ? yours : live.filter((i) => i.move !== 'person') const list = state.allNotes ? shown : shown.slice(0, 5) const about = (i: Insight) => (i.about ? d.techs.find((t) => t.id === i.about)?.name : null) const send = async () => { const text = state.idea.trim() if (!text) return const out = await treeOp('idea kept', 'idea', {goal: g.id, text}) if (out) state.idea = '' } // Folded, a line of counts beside What next: the tree gets the height. if (!state.notesOpen) { return (
    Notes {live.length ? `${live.length} on this goal${yours.length ? `, ${yours.length} yours` : ''}` : 'None yet'} {elsewhere ? ` · ${elsewhere} on single techs (⚑)` : ''}
    ) } return ( (state.notesOpen = false)}> Fold ▴ } >
    {yours.length && yours.length < live.length ? seg( [ {id: 'all', name: 'All'}, {id: 'person', name: `Yours · ${yours.length}`}, {id: 'scout', name: `The scout's · ${live.length - yours.length}`}, ], state.notesBy, (id) => (state.notesBy = id as typeof state.notesBy), ) : null} {list.length ? (
    {list.map((i) => { const open = state.openNote === i.id return (
    {i.move === 'person' ? 'you' : 'scout'} {open && i.evidence.length ? (
      {i.evidence.map((e) => (
    • {e}
    • ))}
    ) : null}
    ) })}
    ) : (

    None yet.

    )} {shown.length > 5 ? ( ) : null} {elsewhere ?

    + {elsewhere} on single techs, shown with ⚑ on the tree

    : null}
    ) } // ── A goal's own page ─────────────────────────────────────────────────────── const editing = local({id: '', loaded: '', name: '', statement: '', who: '', signs: '', never: [] as string[], parent: '', repos: {} as Record, sending: false, picked: false, more: false}) function editPage(d: TreeState, id: string, parent: string): m.Children { const g = d.goals.find((x) => x.id === id) const key = `${id}/${parent}` if (editing.loaded !== key && !editing.sending) { Object.assign(editing, { id: g?.id ?? '', loaded: key, name: g?.name ?? '', statement: g?.statement ?? '', who: g?.who ?? '', signs: g?.signs ?? '', never: g?.never ?? [], parent: g?.parent ?? parent, repos: Object.fromEntries((g?.repos ?? d.goals.find((x) => x.id === parent)?.repos ?? []).map((r) => [r, true])), picked: false, more: !!(g?.who || g?.signs || g?.never.length), }) } // A new goal is about the project shown, or the workspace's one project, until the person says otherwise; a theme reads its goal's. const one = shown() || (projects.list.length === 1 ? projects.list[0].repo : '') if (!g && !editing.parent && !editing.picked && !Object.keys(editing.repos).length && one) editing.repos = {[one]: true} const repos = projects.list.filter((p) => editing.repos[p.repo]).map((p) => p.repo) // Saving sends the scout when it gives the scout its first projects to read (docs/mockups/scout 7-start). const scouts = repos.length > 0 && (!g || !repos_(d, g).length) const save = async () => { editing.sending = true const out = await treeOp(g ? 'goal saved' : 'goal made', 'goal_save', { id: editing.id, name: editing.name, statement: editing.statement, who: editing.who, signs: editing.signs, never: editing.never, parent: editing.parent || null, repos, }) editing.sending = false if (out) { state.goal = g?.id ?? out.last_goal ?? '' editing.loaded = '' const made = out.goals.find((x) => x.id === state.goal) if (scouts && made) await look(made) go('research') } } const remove = async () => { if (!g) return const yes = await askConfirm({title: `Delete “${g.name}”?`, text:

    The goal goes, and the techs that lead only to it and are not built.

    , yes: 'Delete', danger: true}) if (!yes) return if (await treeOp('goal deleted', 'goal_delete', {id: g.id})) { state.goal = '' go('research') } } const above = d.goals.find((x) => x.id === editing.parent) return (

    ← Research

    {SCOUT_ICON} Where should the scout look?

    The scout reads these projects' code, without changing it, and fills the tree in: what is built, what comes next.

    {repoChips(editing.repos, (r) => { editing.picked = true editing.repos = {...editing.repos, [r]: !editing.repos[r]} })} {above && !repos.length ? None picked: it reads those of “{above.name}”. : null}
    {editing.more ? [ , , , ] : null}
    {g ? ( ) : null}
    ) } /** ← → step through the goal and its themes, Escape closes a tech's popover; never while typing or in a dialog. */ function onKey(e: KeyboardEvent) { const d = state.data const el = e.target as HTMLElement | null if (!d || e.altKey || e.ctrlKey || e.metaKey || state.picked || here() !== 'research') return if (el && (el.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(el.tagName))) return if (e.key === 'Escape' && (state.pop || state.menu)) { state.pop = '' state.menu = false m.redraw() return } if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return const g = pickedGoal(d) if (!g) return const line = stops(d, g) if (line.length < 2) return // A theme under a theme steps as the theme it is under. let at = line.findIndex((x) => x.id === g.id) for (let up: Goal | undefined = g; at < 0 && up; up = d.goals.find((x) => x.id === up!.parent)) at = line.findIndex((x) => x.id === up!.id) show(line[(Math.max(0, at) + (e.key === 'ArrowRight' ? 1 : -1) + line.length) % line.length]!.id) e.preventDefault() m.redraw() } export class ResearchPage extends MithrilComponent { oninit() { askProjects() load() } oncreate() { document.addEventListener('keydown', onKey) window.addEventListener('resize', onResize) } onremove() { document.removeEventListener('keydown', onKey) window.removeEventListener('resize', onResize) } view() { const d = state.data if (!d) return

    {state.error || 'Loading the research tree…'}

    const h = here() if (h === 'research/directions') return directionsPage(d) if (h === 'research/map' || h.startsWith('research/map/')) return mapView(d, h) const edit = h.match(/^research\/g\/(g\d+|new)(?:\/(g\d+))?$/) if (edit) return editPage(d, edit[1] === 'new' ? '' : edit[1]!, edit[2] ?? '') const g = pickedGoal(d) if (!g) { const p = projectName(shown()) return (
    {goalProjects(d)} {directionsLink(d)}

    Start with a goal: a sentence of yours, as abstract as you like (“an open metaverse for communities”). The scout then reads its projects and fills in what is built, what it needs next and what earlier sessions left open.

    ) } const techs = techsOf(d, g.id, state.showDropped) const dropped = techsOf(d, g.id, true).length - techsOf(d, g.id).length return (
    {goalBar(d, g)} {directionOf(d, g)?.reached ? null : directionCard(d, directionOf(d, g))} {treeView(d, g, techs)}
    {whatNext(d, g, techs)} {historyCard(techs)} {notesCard(d, g)}
    {dropped ? (

    { e.preventDefault() state.showDropped = !state.showDropped }}> {state.showDropped ? 'Hide' : 'Show'} {dropped} you said “not this” to

    ) : null} {techDialog(d)} {formDialog()}
    ) } }