git clone https://garage44.eu/jeroen/midas.git.. /web/src/components/research.tsx
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<string, boolean>,
// A field's edit that Undo answered (`<tech>:<field>` → that answer's time), so the undo itself shows as no change.
undone: {} as Record<string, number>,
})
let timer: ReturnType<typeof setTimeout> | 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<string, unknown>, quiet = false): Promise<TreeState | null> {
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<TechState, string> = {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<TechState, string> = {
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<string, string> = {
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<string, string> = {S: 'about one session', M: 'two or three sessions', L: 'more: split before it is researched'}
const SIZE_SHORT: Record<string, string> = {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<string, string> = {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 (
<span class="tree-decide">
<button type="button" class="tree-decide__drop" disabled={!steers()} title="Not this: kept off the tree" onclick={() => void treeOp(`not this: ${t.name}`, 'tech_drop', {id: t.id, why: ''})}>
Not this
</button>
<button type="button" class="tree-decide__keep" disabled={!steers()} title="Keep it: out of the fog, so it can be built" onclick={() => void treeOp(`kept: ${t.name}`, 'tech_confirm', {id: t.id})}>
Keep
</button>
</span>
)
}
/** 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: (
<p>
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.
</p>
),
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 ? <span class={cls}>{m.trust(t.icon)}</span> : <span class={`${cls} ${cls}--letter`}>{t.name.slice(0, 1).toUpperCase()}</span>
}
/**
* 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 (
<button
type="button"
class={`tree-tab tree-theme-${slot < 0 ? 'none' : slot}${on ? ' tree-tab--on' : ''}`}
aria-current={x.id === g.id ? 'page' : undefined}
// On a phone the row scrolls sideways: keep the chosen one in sight.
oncreate={x.id === g.id ? (v: m.VnodeDOM) => (v.dom as HTMLElement).scrollIntoView({block: 'nearest', inline: 'nearest'}) : undefined}
title={x.statement || x.name}
onclick={() => show(x.id)}
>
<span class="tree-tab__name">
<i class="tree-theme__dot" />
{x.name}
</span>
<span class="tree-tab__bar">
<span style={{width: `${n ? (q.built / n) * 100 : 0}%`}} />
</span>
<small>{n ? `${q.built}/${n}` : 'empty'}</small>
</button>
)
}
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) => (
<button type="button" class="tree-menu__item" disabled={off} onclick={() => {
state.menu = false
onclick()
}}>
{label}
</button>
)
return (
<nav class="tree-bar" aria-label="Goals and themes">
<div class="tree-bar__row">
{goalProjects(d)}
{directionsLink(d)}
<div class={`tree-goalpick${g.id === root.id ? ' tree-goalpick--on' : ''}`}>
<button type="button" class="tree-goalpick__main" title={root.statement || root.name} onclick={() => show(root.id)}>
<span class="tree-head__flag">{GOAL_FLAG}</span>
<span class="tree-goalpick__text">
<b>{root.name}</b>
<small>
{p.built} of {all} built{p.fog ? ` · ${p.fog} ${p.fog === 1 ? 'guess' : 'guesses'}` : ''}
</small>
</span>
</button>
<button type="button" class="tree-goalpick__more" aria-label="Other goals and the goal's tools" aria-expanded={state.menu} onclick={() => (state.menu = !state.menu)}>
▾
</button>
{state.menu ? [
<div class="tree-menu__shade" onclick={() => (state.menu = false)} />,
<div class="tree-menu" role="menu">
{tops.map((x) => item([GOAL_FLAG, <span>{x.name}</span>], () => show(x.id)))}
{tops.length ? <hr /> : null}
{item(`Edit “${shortName(g.name, 28)}”`, () => go(`research/g/${g.id}`), !steers())}
{item(`Add a theme to “${shortName(root.name, 22)}”`, () => go(`research/g/new/${root.id}`), !steers())}
{item('New goal', () => go('research/g/new'), !steers())}
</div>,
] : null}
</div>
<div class="tree-tabs">{rowOf(root)}</div>
</div>
{deeper.map((x) => (
<div class="tree-bar__row tree-bar__row--under">
<span class="tree-nav__under">under “{x.name}”</span>
<div class="tree-tabs">{rowOf(x)}</div>
</div>
))}
</nav>
)
}
/** 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<string>()
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 ', <code>{x.text}</code>, ` in ${x.repo}`]
case 'search':
return ['Searching for “', <b>{x.text}</b>, `”${x.in ? ` in ${x.in}` : ''} in ${x.repo}`]
default:
return ['Listing ', <code>{x.text}</code>, ` 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<string, unknown> = {}) {
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 = (
<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<circle cx="7" cy="15" r="3.5" />
<circle cx="17" cy="15" r="3.5" />
<path d="M10.5 15h3M5 12l2-6h3l.5 6M19 12l-2-6h-3l-.5 6" />
</svg>
)
/**
* 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 (
<div class="tree-scoutbar tree-scoutbar--going tree-scoutbar--live">
<div class="tree-scoutbar__line tree-scoutbar__line--one">
<span class="tree-scoutbar__av tree-scoutbar__av--going">{SCOUT_ICON}</span>
<span class="tree-scoutbar__who">
<b>The scout is looking</b>
<small>
at {about ? `“${about.name}”` : `“${at?.name ?? g.name}”`} · {age(going.at)}
</small>
</span>
<span class="tree-asked tree-asked--one" title={asked(going)}>
<small>You asked</small>
{asked(going) || 'what is built, what comes next, what earlier sessions left open'}
</span>
<span class="tree-pips" title={moves.map((r) => `${stepWord(d, r, names)}: ${r.state === 'asked' ? 'now' : r.state}`).join(' · ')}>
{moves.map((r) => (
<i class={`tree-pip tree-pip--${r.state}`} />
))}
</span>
<span class="tree-reading">
<i class="tree-spin" />
{reading ? [reading.kind === 'read' ? 'reading ' : 'searching ', <code>{reading.kind === 'read' ? reading.text.split('/').slice(-2).join('/') : reading.text}</code>] : now ? stepWord(d, now, names).toLowerCase() : 'waiting its turn'}
</span>
{waiting.length ? <span class="tree-waiting__count">+{waiting.length} after this</span> : null}
<Button variant="ghost" class="tree-scoutbar__more" onclick={() => (state.scoutOpen = !state.scoutOpen)}>
{state.scoutOpen ? 'Details ▴' : 'Details ▾'}
</Button>
<Button variant="ghost" disabled={!steers()} onclick={() => void treeOp('the scout stopped', 'look_stop', {look: going.id})}>
Stop
</Button>
</div>
{state.scoutOpen ? scoutDetails() : null}
</div>
)
function scoutDetails(): m.Children {
return (
<div class="tree-scoutdetails">
<p class="tree-scoutdetails__asked">
<small>You asked{going.via === 'talk' ? ' · in the conversation' : ''}</small>
{asked(going) || 'Research further: what is built, what comes next, what earlier sessions left open'}
</p>
<span class="tree-steps">
{going.rounds.map((r) => (
<span class={`tree-step-chip tree-step-chip--${r.state}`} title={r.state === 'failed' ? (r.error ?? '') : undefined}>
{r.state === 'done' ? '✓ ' : r.state === 'failed' ? '✕ ' : null}
{r.state === 'asked' ? <i class="tree-spin" /> : null}
{stepWord(d, r, names)}
{r.state === 'skipped' ? ': not needed' : null}
{r.live && (r.live.reads || r.live.searches) ? <small> · {readCount(r.live)}</small> : null}
</span>
))}
<small class="hint">{timeLeft(d, going)}</small>
</span>
{live && (live.lines.length || live.thought) ? (
<div class="tree-live">
{live.lines.slice(0, LIVE_SHOWN).map((x, i) => (
<div class={`tree-live__line${i === 0 ? ' tree-live__line--now' : ''}`}>
<span class="tree-live__at">{i === 0 ? 'now' : age(x.at)}</span>
<span>{liveWord(x)}</span>
</div>
))}
{live.thought ? (
<blockquote class="tree-live__thought">
“{live.thought}”
<small>What it said last while reading: a guess until it is back</small>
</blockquote>
) : null}
</div>
) : now ? (
<p class="hint tree-live tree-live--quiet">It has just started reading; what it reads shows here as it goes.</p>
) : null}
<div class="tree-waiting">
<small>After this</small>
{waiting.map((l) => (
<span class="tree-waiting__q">
{asked(l) || 'Research further'}
{l.via === 'talk' ? <small> · in the conversation</small> : null}
<button type="button" class="tree-insight__drop" title="Take it back" disabled={!steers()} onclick={() => void treeOp('taken back', 'look_stop', {look: l.id}, true)}>
×
</button>
</span>
))}
{/* A question asked now waits for this look and goes by itself after it. */}
<span class="tree-scoutbar__ask">
<FieldText model={bind(state, 'ask')} placeholder="Ask something after this" disabled={!steers()} />
</span>
{state.ask.trim() ? (
<Button variant="secondary" disabled={!steers()} onclick={() => void look(g, {focus: state.ask.trim()}).then((out) => out && (state.ask = ''))}>
Ask after this
</Button>
) : null}
</div>
</div>
)
}
}
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 ? <span class={`tree-found tree-found--${tone}`}>{n} {word}</span> : null)
const newOnes = c.added.filter((id) => !c.built.includes(id)).length
return (
<div class="tree-scoutbar tree-scoutbar--back">
<div class="tree-scoutbar__line">
<span class="tree-scoutbar__av tree-scoutbar__av--back">{SCOUT_ICON}</span>
<span class="tree-scoutbar__who">
<b>The scout is back</b>
<small>{age(shown.ended) === 'now' ? 'just now' : `${age(shown.ended)} ago`}</small>
</span>
<span class="tree-steps">
{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')}
</span>
{finds.length ? (
<span class="tree-walk">
<Button variant="ghost" aria-label="The one before" onclick={() => walkTo(d, shown, state.walk < 0 ? finds.length - 1 : state.walk - 1)}>
‹
</Button>
<small>{state.walk < 0 ? `${finds.length} to see` : `${state.walk + 1} of ${finds.length}`}</small>
<Button variant="ghost" aria-label="The next one" onclick={() => walkTo(d, shown, state.walk + 1)}>
›
</Button>
</span>
) : null}
<Button variant="primary" onclick={() => {
state.walk = -1
state.focus = ''
void treeOp('seen', 'look_seen', {look: shown.id}, true)
}}>
Seen it
</Button>
</div>
{at ? (
<p class="tree-scoutbar__find">
<b>{at.kind}:</b> {at.note ? at.note.text : at.tech ? [<button type="button" class="tree-move__open" onclick={() => pick(at.tech!.id)}>{at.tech.name}</button>, at.tech.what ? ` — ${at.tech.what}` : ''] : null}
</p>
) : null}
</div>
)
}
const last = looks.at(-1)
return (
<div class="tree-scoutbar">
<span class="tree-scoutbar__av">{SCOUT_ICON}</span>
<span class="tree-scoutbar__who">
<b>The scout</b> reads {names} and fills in the tree.
<small>{last ? `Last look ${age(last.ended ?? last.at)} ago: ${lookWord(last)}.` : 'It has not looked yet.'}</small>
</span>
<span class="tree-scoutbar__ask">
<FieldText model={bind(state, 'ask')} placeholder="Something to look at? (optional)" disabled={!steers()} />
</span>
{talkAboutTree() ? (
<Button variant="ghost" class="tree-scoutbar__mic" disabled={!steers()} title="Talk it over: say what the scout should look at" onclick={() => openTreeTalk()}>
🎙
</Button>
) : null}
<Button variant="primary" disabled={!steers()} onclick={() => void look(g, {focus: state.ask.trim()}).then((out) => out && (state.ask = ''))}>
Research further
</Button>
</div>
)
}
/** The workspace's projects as chips to pick, on in the scout's colour. */
function repoChips(on: Record<string, boolean>, flip: (repo: string) => void): m.Children {
return (
<div class="tree-repos">
{projects.list.map((p) => (
<button type="button" class={`chooser tree-repo${on[p.repo] ? ' tree-repo--on' : ''}`} aria-pressed={!!on[p.repo]} disabled={!steers()} onclick={() => flip(p.repo)}>
{on[p.repo] ? '✓ ' : ''}
{p.name}
</button>
))}
</div>
)
}
/**
* 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 (
<div class="tree-scoutstart">
<div class="tree-scoutstart__head">
<span class="tree-scoutbar__av">{SCOUT_ICON}</span>
<b>The scout doesn't know where to look yet</b>
</div>
<ol class="tree-scoutstart__steps">
<li class="tree-scoutstart__step tree-scoutstart__step--now">
<span>Pick the project(s) this goal is about</span>
{repoChips(state.startRepos, (r) => (state.startRepos = {...state.startRepos, [r]: !state.startRepos[r]}))}
</li>
<li class="tree-scoutstart__step">Send the scout: it reads their code, without changing it, for a few minutes</li>
<li class="tree-scoutstart__step">Cards appear on the tree: what is built, and what comes next</li>
</ol>
<div class="tree-scoutstart__go">
<FieldText model={bind(state, 'ask')} placeholder="Anything in particular? (optional)" disabled={!steers()} />
<Button variant="primary" disabled={!steers() || !picked.length} onclick={() => void send()}>
Send the scout
</Button>
</div>
</div>
)
}
/**
* 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 (
<div class="tree-firstlook">
<ol class="tree-scoutstart__steps">
<li class="tree-scoutstart__step tree-scoutstart__step--done">Projects picked: {names}</li>
<li class="tree-scoutstart__step tree-scoutstart__step--now">
Reading the code{[counted, left].filter(Boolean).length ? ` — ${[counted, left].filter(Boolean).join(', ')}` : ''}
</li>
<li class="tree-scoutstart__step">Cards on the tree</li>
</ol>
<p class="hint">The tree fills in here as the scout finds things. You can leave this page: it carries on.</p>
<div class="tree-firstlook__cards" aria-hidden="true">
<i />
<i />
<i />
</div>
</div>
)
}
/** 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 (
<div class="tree-log">
<div class="tree-log__row">
<span class="tree-log__title">Scout's log</span>
{list.map((l) => (
<button
type="button"
class={`tree-log__chip${l.id === state.lookShown ? ' tree-log__chip--on' : ''}${brought(l) ? '' : ' tree-log__chip--empty'}`}
title={l.focus ? `Looking at: ${l.focus}` : undefined}
onclick={() => {
state.lookShown = state.lookShown === l.id ? '' : l.id
state.walk = -1
state.focus = ''
}}
>
<i />
{age(l.ended ?? l.at)} · {lookWord(l)}
</button>
))}
{looks.length > 4 ? (
<button type="button" class="tree-past" onclick={() => (state.allLooks = !state.allLooks)}>
{state.allLooks ? 'Fewer' : `All ${looks.length}`}
</button>
) : null}
</div>
{open ? (
<p class="hint tree-log__text">
{open.focus ? <span>Looking at: {open.focus}. </span> : null}
{text || 'It said nothing more.'}
</p>
) : null}
</div>
)
}
/** 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 (
<div class="tree-ask">
<div class="tree-detail__label">Have the scout look further at this</div>
<div class="tree-ask__chips">
{ASKS.filter((a) => a.when(t)).map((a) => (
<button type="button" class="tree-ask__chip" disabled={off} onclick={() => send(a.ask)}>
{a.word}
</button>
))}
</div>
<div class="tree-ask__own">
<FieldText model={bind(state, 'popAsk')} placeholder="Or ask in your own words" disabled={off} />
<Button variant="secondary" disabled={off || !state.popAsk.trim()} onclick={() => send('own', state.popAsk.trim())}>
Ask
</Button>
</div>
{looksFor(d, g).some((l) => l.going) ? <small class="hint">The scout is looking already: this waits for it and goes after it by itself.</small> : null}
</div>
)
}
/**
* 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 (
<div
class="tree-pop"
onclick={(e: Event) => 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)
}}
>
<div class="tree-pop__head">
{iconOf(t)}
<b>{t.name}</b>
<span class={`tree-row__state tree-row__state--${t.state}`}>
{STATE_WORD[t.state]}
{t.state === 'built' ? '' : ` · ${t.size}`}
</span>
<button type="button" class="tree-insight__drop" aria-label="Close" onclick={() => (state.pop = '')}>
×
</button>
</div>
{t.what ? <p class="tree-pop__what">{t.what}</p> : null}
<div class="tree-pop__tools">
{decide(t)}
{t.state === 'available' || t.state === 'locked' ? (
<Button variant="secondary" disabled={!steers()} onclick={() => void research(t)}>
Start building
</Button>
) : null}
{t.state === 'researching' && t.research ? (
<Button variant="secondary" onclick={() => openResearch(t)}>
Open session
</Button>
) : null}
<Button variant="ghost" onclick={() => pick(t.id)}>
Open ›
</Button>
</div>
{askScout(d, g, t)}
</div>
)
}
/** 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 (
<div class={`tree-move tree-move--${kind}`}>
<span class="tree-move__icon">{icon}</span>
<span class="tree-move__text">
<span class="tree-move__title">{title}</span>
{sub ? <small>{sub}</small> : null}
</span>
<span class="tree-move__tools">{tools}</span>
</div>
)
}
/** 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(
<section class="tree-next">
<h3 class="tree-next__label">
{title}
{sub ? <small>{sub}</small> : null}
</h3>
<div class="tree-moves">{lines}</div>
</section>,
)
}
const name = (t: Tech) => (
<button type="button" class="tree-move__open" onclick={() => pick(t.id)}>
{t.name}
</button>
)
const icon = (t: Tech) => <span class={themeClass(of, t.id)}>{iconOf(t)}</span>
// 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`, (
<Button variant="ghost" disabled={!steers()} onclick={() => void treeOp('direction closed', 'direction_clear', {}, true)}>
Close
</Button>
)),
)
}
if (!repos_(d, g).length) {
yours.push(
moveLine('ask', GOAL_FLAG, 'Say which projects this goal is about', 'The scout reads only those.', (
<Button variant="primary" disabled={!steers()} onclick={() => go(`research/g/${rootOf(d, g).id}`)}>
Edit goal
</Button>
)),
)
}
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', <i class="tree-theme__dot" />, `Theme: ${p.name}`, p.statement || `${names.length} techs: ${names.slice(0, 3).join(', ')}${names.length > 3 ? ` and ${names.length - 3} more` : ''}`, (
<span class="tree-decide">
<button type="button" class="tree-decide__drop" disabled={!steers()} onclick={() => void treeOp('theme dropped', 'proposal_drop', {id: p.id}, true)}>
Not this
</button>
<button type="button" class="tree-decide__keep" disabled={!steers()} onclick={() => void treeOp(`theme kept: ${p.name}`, 'proposal_accept', {id: p.id})}>
Keep
</button>
</span>
)),
)
}
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
? [
<span class="way-tag way-tag--now">{nowTag(t)}</span>,
t.research ? (
<Button variant="ghost" onclick={() => openResearch(t)}>
Open session
</Button>
) : null,
]
: t.state === 'available'
? [
t.id === nextId ? <span class="way-tag way-tag--next">next</span> : null,
<Button variant={heading ? 'ghost' : 'primary'} disabled={!steers()} onclick={() => void research(t)}>
Start now
</Button>,
]
: t.id === nextId
? <span class="way-tag way-tag--next">next</span>
: null
return (
<div class={`tree-step tree-step--${now ? 'now' : after.length ? 'later' : 'ready'}`}>
<span class="tree-step__n">{now ? '▶' : n}</span>
{moveLine(now ? 'now' : after.length ? 'later' : 'ready', icon(t), name(t), sub, tools)}
</div>
)
}
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 ? (
<div class="tree-next__head">
<span>
<b>{toBuild} still to build</b> for this goal{ready.length ? `, ${ready.length} can start now` : ''}. Midas can build them one after another by itself, on autopilot.
</span>
<Button variant="primary" disabled={!steers()} onclick={() => headFor(d, g.id, g.name)}>
Build it all by itself
</Button>
</div>
) : 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 (
<Card class={`tree-fold-card${open ? ' tree-fold-card--open' : ''}`}>
<div class="tree-next__fold">
<b class="tree-board__title">What next</b>
<span class="hint">{empty ? 'Everything known is built: Research further, above, finds what comes next.' : summary || 'Nothing waits on you.'}</span>
{!open && head ? (
<Button variant="primary" disabled={!steers()} onclick={() => headFor(d, g.id, g.name)}>
Build it all by itself
</Button>
) : null}
{empty ? null : (
<Button variant="ghost" aria-expanded={open} onclick={() => (state.nextOpen = !state.nextOpen)}>
{open ? 'Fold ▴' : 'Open ▾'}
</Button>
)}
</div>
{open ? [head, sections] : null}
</Card>
)
}
/** 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<string, string> = {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 (
<Card class={`tree-fold-card${open ? ' tree-fold-card--open' : ''}`}>
<div class="tree-next__fold">
<b class="tree-board__title">How it went</b>
<span class="hint">{summary}</span>
<Button variant="ghost" aria-expanded={open} onclick={() => (state.historyOpen = !state.historyOpen)}>
{open ? 'Fold ▴' : 'Open ▾'}
</Button>
</div>
{open
? [
<h3 class="tree-detail__label">Techs built a week</h3>,
<Bars
days={x.built.map((_, i) => i)}
series={SERIES_BUILT}
value={(i) => [x.built[i]!, x.found[i]!]}
format={(v) => String(Math.round(v))}
label={weekOf}
/>,
x.runs.length ? (
<Table
rowKey={(r: Run) => r.id}
rows={x.runs}
columns={[
{key: 'tech', label: 'tech', cell: (r: Run) => <a href="#" onclick={(e: Event) => { e.preventDefault(); pick(r.tech.id) }}>{shortName(r.tech.name, 40)}</a>},
{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) => <a href={`/sessions/${r.id}`} onclick={(e: Event) => { e.preventDefault(); go(`sessions/${r.id}`) }}>{r.id}</a>},
]}
/>
) : null,
]
: null}
</Card>
)
}
/** To Directions, from the goal bar: how many go. */
function directionsLink(d: TreeState): m.Children {
const n = directionsOf(d).length
return [
<Button variant="ghost" onclick={() => go('research/directions')}>
{n ? `Directions · ${n}` : 'Directions'}
</Button>,
<Button variant="ghost" onclick={() => go('research/map')}>
Map
</Button>,
]
}
/**
* 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 (
<div class="stack">
<div class="tree-bar__row">
<Button variant="ghost" onclick={() => go('research')}>
← The tree
</Button>
<b class="tree-board__title">Directions</b>
<span class="hint">{list.length ? `${list.length} going, over every project` : 'none going'}</span>
</div>
<Card class="tree-budget">
<div class="tree-budget__row">
<div>
<b>Across all directions</b>
<div class="hint">
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
</div>
</div>
<span class="tree-budget__slots" aria-label={`${b.going} of ${b.at_once} at work`}>
{Array.from({length: b.at_once}, (_, i) => (
<i class={i < b.going ? 'on' : ''} />
))}
</span>
<span class="hint">
{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` : ''}
</span>
<Button variant="ghost" disabled={!steers()} onclick={() => changeBudget(d)}>
Budget
</Button>
</div>
</Card>
{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 : <p class="hint">Nothing is researched by itself. Head for a goal: its techs are then built one after another, on autopilot.</p>}
{free.length ? (
<div class="tree-bar__row">
<FieldSelect model={bind(state, 'headGoal')} placeholder="Head for another goal…" options={free.map((g) => ({value: g.id, label: g.name}))} />
<Button
variant="primary"
disabled={!steers() || !state.headGoal}
onclick={() => {
const g = free.find((x) => x.id === state.headGoal)
if (g) headFor(d, g.id, g.name)
}}
>
Head this way
</Button>
</div>
) : null}
{formDialog()}
</div>
)
}
/** 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 = [
<div class="focus-row">
<FieldNumber label="Sessions at once" model={bind(form, 'at_once')} min={1} max={3} help="More than one can collide in one project." />
<FieldNumber label="Started a day" model={bind(form, 'per_day')} min={1} max={12} />
</div>,
<FieldSwitch
model={bind(form, 'scout')}
label="Send the scout when the way runs out"
help="Rather than stop once everything known is built, it looks for what comes next, at most twice a day, and carries on with what it finds."
/>,
<FieldNumber
label="And after every"
model={bind(form, 'scout_every')}
min={0}
max={10}
unit="landings"
disabled={!form.scout}
help="It looks again at what the landings left open. 0: only when the way runs out."
/>,
]
return (
<Dialog
model={open}
title={title}
size="sm"
footer={[
<Button variant="ghost" onclick={() => (form.open = '')}>
Cancel
</Button>,
<Button variant="primary" disabled={!steers()} onclick={() => void submitForm()}>
{yes}
</Button>,
]}
>
<div class="tree-form">
{form.open === 'head' ? (
<p>
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.` : ''}
</p>
) : null}
{form.open === 'head' || form.open === 'limits' ? limits : null}
{form.open === 'budget' ? [
<div class="focus-row">
<FieldNumber label="Sessions at once" model={bind(form, 'b_at_once')} min={1} max={6} />
<FieldNumber label="Started a day" model={bind(form, 'b_per_day')} min={1} max={30} />
</div>,
<FieldNumber
label="At once in one project"
model={bind(form, 'b_per_project')}
min={1}
max={3}
help="Directions that reach the same project take turns there; more than one can collide."
/>,
<p class="hint">Each direction keeps its own limits within these. When they are used up, the direction highest in the list starts next.</p>,
] : null}
{form.open === 'done' ? (
<FieldTextarea
model={bind(form, 'done')}
label="Done when"
placeholder="on the phone, an invite link opens the community for someone without an account"
help="One to three checks you could make yourself. The session gives evidence for each before it asks to land."
/>
) : null}
</div>
</Dialog>
)
}
/** 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 ? <span class="tree-direction__project">{projectName(p) ?? p}</span> : 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) => (
<button type="button" class={`way-stop way-stop--${kind} ${themeClass(themes(d.techs, d.goals, colourGoal(d, pickedGoal(d))).of, t.id)}`} onclick={onclick}>
<span class="way-stop__node">{kind === 'done' ? CHECK : iconOf(t, 'way-stop__icon')}</span>
<span class="way-stop__name">{t.name}</span>
<span class="way-stop__sub">{sub}</span>
</button>
)
return (
<div class={`tree-direction${dir.paused ? ' tree-direction--paused' : ''}${dir.reached ? ' tree-direction--reached' : ''}`}>
<div class="tree-direction__head">
{GOAL_FLAG}
<b>{dir.name}</b>
<span class="tree-direction__count">
<span class="tree-goal__bar">
<span class="tree-goal__bar-built" style={{width: `${share * 100}%`}} />
</span>
{built} / {on.length}
</span>
<span class="tree-direction__tools">
{order ? (
<Button variant="ghost" disabled={!steers() || !order.up} title="Earlier: it starts first when the budget is short" onclick={() => order.up?.()}>
↑
</Button>
) : null}
{order ? (
<Button variant="ghost" disabled={!steers() || !order.down} title="Later" onclick={() => order.down?.()}>
↓
</Button>
) : null}
{dir.reached ? null : (
<Button variant="ghost" disabled={!steers()} onclick={() => changeLimits(dir)}>
Limits
</Button>
)}
{dir.reached ? null : (
<Button variant="ghost" disabled={!steers()} onclick={() => void treeOp(dir.paused ? 'resumed' : 'paused', 'direction_pause', {id: dir.id, paused: !dir.paused})}>
{dir.paused ? 'Resume' : 'Pause'}
</Button>
)}
<Button variant="ghost" disabled={!steers()} onclick={() => void treeOp('direction cleared', 'direction_clear', {id: dir.id})}>
{dir.reached ? 'Done' : 'Stop'}
</Button>
</span>
</div>
<div class="way">
{lastLanded ? stop('done', lastLanded, techPips(lastLanded), () => pick(lastLanded.id)) : null}
{going.map((t) =>
stop(
'now',
t,
[<span class="way-tag way-tag--now">{nowTag(t)}</span>, techPips(t), where(repoOf(t))],
() => openResearch(t),
),
)}
{dir.next?.why === 'scouting' ? (
<div class="way-stop way-stop--scout">
<span class="way-stop__node">{SCOUT_MARK}</span>
<span class="way-stop__name">The scout looks ahead</span>
<span class="way-stop__sub">{dir.scouted?.why === 'every' ? `after ${dir.scout_every} landings` : 'the way ran out'} · nothing starts meanwhile</span>
</div>
) : null}
{next && dir.next ? stop('next', next, [<span class="way-tag way-tag--next">next</span>, nextWord(d, dir.next), where(dir.next.project)], () => pick(next.id)) : null}
<div class={`way-stop way-stop--goal`}>
<span class="way-stop__node">{GOAL_FLAG}</span>
<span class="way-stop__name">{dir.reached ? 'Reached' : 'The goal'}</span>
<span class="way-stop__sub">{dir.reached ? null : `${on.length - built} to go`}</span>
</div>
</div>
{dir.paused ? <span class="tree-caveat">{dir.paused}</span> : null}
{dir.reached ? null : (
<span class="hint tree-direction__limits">
{order && projects.length ? `${projects.map((p) => projectName(p) ?? p).join(', ')} · ` : ''}
{limitsLine(dir)}
</span>
)}
</div>
)
}
const SCOUT_MARK = (
<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<circle cx="10.5" cy="10.5" r="6" />
<path d="M15 15l5 5" />
</svg>
)
const CHECK = (
<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M5 12.5l4.5 4.5L19 7.5" />
</svg>
)
const GOAL_FLAG = (
<svg class="tree-goal-mark" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M5 21V4" />
<path d="M5 4h12l-2.5 4.5L17 13H5" />
</svg>
)
/**
* 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<string, number>, 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 (
<li class={`tree-branch__node ${themeClass(of, t.id)}${b.children.length ? '' : ' tree-branch__node--leaf'}`}>
<button
type="button"
class={`tree-row tree-row--${t.state}${lit ? (lit.has(t.id) ? ' tree-row--lit' : ' tree-row--dim') : ''}${t.id === focus ? ' tree-row--focus' : ''}${x.fresh.has(t.id) ? ' tree-row--new' : ''}`}
data-tech={t.id}
onclick={() => pick(t.id)}
>
{iconOf(t)}
<span class="tree-row__text">
<span class="tree-row__name">{t.name}</span>
{/* Under the name too: beside it, "in the fog · M" kept its width and a deep branch's name went one letter to a line. */}
{t.state === 'built' || t.state === 'researching' || t.id === x.next ? null : (
<small class={`tree-row__state tree-row__state--${t.state}`}>{`${STATE_WORD[t.state]} · ${t.size}`}</small>
)}
{b.also.length ? <small class="tree-row__also">also needs {b.also.map((n) => n.name).join(', ')}</small> : null}
{caveats ? <small class="tree-caveat">{caveatWord(caveats)}</small> : null}
{/* Under the name, not beside it: beside it the tag took half a phone's width and the name went to four lines. */}
{t.state === 'researching' ? (
<span class="way-tag way-tag--now tree-row__tag">{nowTag(t)}</span>
) : t.id === x.next ? (
<span class="way-tag way-tag--next tree-row__tag">next</span>
) : null}
</span>
{t.state === 'built' && t.id !== x.next ? <span class="tree-row__state tree-row__state--built">✓</span> : null}
</button>
{decide(t)}
{b.children.length ? <ul class="tree-branch">{b.children.map((c) => branchRow(c, x))}</ul> : null}
</li>
)
}
/** What a drawing of the tree shares: the lit line, the focused tech, each tech's theme. */
interface Drawn {
d: TreeState
lit: Set<string> | null
focus: string
of: Map<string, number>
/** The tech the direction starts next. */
next: string
/** What the scout's last look brought, still glowing. */
fresh: Set<string>
}
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 (
<div class="tree-board">
{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) : <p class="hint tree-empty">Nothing on the tree yet: Research further fills it in.</p>}
{lookLog(d, g)}
</div>
)
}
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 (
<div class="tree-board">
{/* Themes are chosen above the page (goalNav); here a colour only says which branch a card is on. */}
<div class="tree-legend">
<b class="tree-board__title">The tree</b>
{/* Counts only: what a state means is its tooltip. */}
{(['built', 'researching', 'available', 'locked', 'fog'] as TechState[]).filter((s) => counts(s)).map((s) => (
<span class={`tree-legend__item tree-legend__item--${s}`} title={STATE_MEANS[s]}>
<i class="tree-legend__swatch" />
<b>{counts(s)}</b> {s === 'fog' ? (counts(s) === 1 ? 'guess' : 'guesses') : STATE_WORD[s]}
</span>
))}
{open && (hidden || state.allBuilt) ? (
<button type="button" class="tree-past" title="Built techs nothing open stands on are left out" onclick={() => (state.allBuilt = !state.allBuilt)}>
{state.allBuilt ? 'Only what is open' : `Show the other ${hidden} built`}
</button>
) : null}
</div>
{scoutBar(d, g)}
<div class="tree-outline">
<ul class="tree-branch">{branches(techs).map((b) => branchRow(b, drawn))}</ul>
<div class="tree-outline__goal">
{GOAL_FLAG}
<span>
<small>All of it leads to</small>
<b>{g.name}</b>
</span>
</div>
</div>
<div
class="tree-scroll tree-graph"
title="A line runs from what a tech needs to the tech. Tap one to light its line and read about it."
oncreate={(v: m.VnodeDOM) => measureFill(v.dom)}
onupdate={(v: m.VnodeDOM) => measureFill(v.dom)}
onpointerdown={grab}
>
<div
class={`tree-canvas${lit ? ' tree-canvas--focus' : ''}`}
style={{width: `${l.width}px`, height: `${l.height}px`}}
onclick={(e: Event) => {
if (e.target === e.currentTarget && performance.now() - pulled > 300) {
state.focus = ''
state.pop = ''
}
}}
>
{l.lanes.map((x) => {
const theme = th.list[x.band]
return (
<div
class={`tree-lane ${theme ? `tree-theme-${theme.slot < 0 ? 'none' : theme.slot}` : 'tree-theme-none'}${scout && theme?.goal === scout.look.goal ? ' tree-lane--scout' : ''}`}
style={{top: `${x.y}px`, height: `${x.h}px`, width: `${l.goal.x - 16}px`}}
>
{theme?.goal ? (
<button type="button" class="tree-lane__name" style={{height: `${LANE_HEAD}px`}} title="Show this theme alone" onclick={() => show(theme.goal!)}>
<i class="tree-theme__dot" />
{theme.name}
{scout && theme.goal === scout.look.goal ? <small class="tree-lane__scout">the scout looks here</small> : null}
</button>
) : (
<span class="tree-lane__name" style={{height: `${LANE_HEAD}px`}}>
{laneName(x.band)}
</span>
)}
</div>
)
})}
{l.cols.map((x, i) => (
<div class="tree-col-head" style={{left: `${x}px`, width: `${CARD_W}px`, height: `${HEAD_H}px`}}>
{i === 0 ? 'Needs nothing' : `Step ${i + 1}`}
</div>
))}
<div class="tree-col-head tree-col-head--goal" style={{left: `${l.goal.x}px`, width: `${l.goal.w}px`, height: `${HEAD_H}px`}}>
The goal
</div>
<svg class="tree-lines" width={l.width} height={l.height} aria-hidden="true">
{l.edges.map((e) => (
<path class={`tree-line tree-line--${e.kind} ${themeClass(th.of, e.a)}${edgeLit(e.a, e.b) ? ' tree-line--lit' : ''}`} d={curve(e)} />
))}
</svg>
{l.cards.map((c) => (
<button
type="button"
class={`tree-card tree-card--${c.tech.state} ${themeClass(th.of, c.tech.id)}${lit ? (lit.has(c.tech.id) ? ' tree-card--lit' : ' tree-card--dim') : ''}${c.tech.id === focus ? ' tree-card--focus' : ''}${fresh.has(c.tech.id) || nowBuilt.has(c.tech.id) ? ' tree-card--new' : ''}${c.tech.id === reading ? ' tree-card--reading' : wasRead.has(c.tech.id) ? ' tree-card--read' : ''}`}
data-tech={c.tech.id}
style={{left: `${c.x}px`, top: `${c.y}px`, width: `${CARD_W}px`, height: `${CARD_H}px`}}
title={c.tech.id === reading ? `The scout reads ${scout?.reading} now` : c.tech.what || c.tech.name}
onmouseenter={() => (state.hover = c.tech.id)}
onmouseleave={() => (state.hover = '')}
onclick={(e: Event) => {
e.stopPropagation()
state.focus = c.tech.id
state.pop = state.pop === c.tech.id ? '' : c.tech.id
state.popAsk = ''
}}
>
{c.tech.state === 'researching' ? <span class="way-tag way-tag--now tree-card__tag">{nowTag(c.tech)}</span> : null}
{c.tech.id === nextId ? <span class="way-tag way-tag--next tree-card__tag">next</span> : null}
{nowBuilt.has(c.tech.id) ? <span class="way-tag way-tag--built tree-card__tag">now built</span> : fresh.has(c.tech.id) ? <span class="way-tag way-tag--new tree-card__tag">{shown?.going ? 'just found' : 'new'}</span> : null}
{c.tech.id === reading ? (
<span class="way-tag way-tag--reading tree-card__tag">
{SCOUT_ICON}
reading this
</span>
) : wasRead.has(c.tech.id) ? (
<span class="way-tag way-tag--read tree-card__tag">✓ read</span>
) : null}
{iconOf(c.tech)}
<span class="tree-card__text">
<span class="tree-card__name">{c.tech.name}</span>
<small>
{c.tech.state === 'researching' ? techPips(c.tech) : STATE_WORD[c.tech.state]}
{c.tech.state === 'built' || c.tech.state === 'researching' ? '' : ` · ${c.tech.size}`}
{caveatsOf(d, c.tech.id).length ? <span class="tree-caveat"> · {caveatsOf(d, c.tech.id).length} ⚑</span> : null}
</small>
</span>
</button>
))}
<div class="tree-card tree-card--goal" style={{left: `${l.goal.x}px`, top: `${l.goal.y}px`, width: `${l.goal.w}px`, height: `${l.goal.h}px`}}>
{GOAL_FLAG}
<span class="tree-card__name">{g.name}</span>
{g.parent ? (
<button type="button" class="tree-card__up" title="Back to the goal this is a theme of" onclick={() => show(g.parent!)}>
↑ a theme of {shortName(d.goals.find((x) => x.id === g.parent)?.name ?? 'its goal', 34)}
</button>
) : (
<small>everything on the tree leads here</small>
)}
</div>
{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 (
<button
type="button"
class="tree-ghost"
style={{left: `${x.x}px`, top: `${x.y}px`, width: `${CARD_W}px`, height: `${CARD_H}px`}}
disabled={busy || !target}
title={theme ? `Have the scout look further at “${theme.name}”` : 'Have the scout look for what comes next'}
onclick={(e: Event) => {
e.stopPropagation()
if (target) void look(target, {focus: 'What comes next, after what the tree has now?'})
}}
>
<span class="tree-ghost__plus">+</span>
<span>
Look further here
<small>what comes next?</small>
</span>
</button>
)
})}
</div>
</div>
{popAt ? popover(d, g, popAt.tech) : null}
{lookLog(d, g)}
</div>
)
}
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 <Dialog model={open} title="" />
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) => (
<button type="button" class={`tree-node tree-node--${x.state}`} onclick={() => pick(x.id)}>
{iconOf(x)}
<span>{x.name}</span>
<small>{STATE_WORD[x.state]}</small>
</button>
)
const sessionLink = (id: string) => (
<a href={`/sessions/${id}`} class="home__link" onclick={(e: Event) => {
e.preventDefault()
close()
go(`sessions/${id}`)
}}>
{id}
</a>
)
// 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) ? (
<span class="hint">The scout is drawing it{remarks.length ? '' : '…'}</span>
) : talking() ? null : (
<button type="button" class="tree-past" disabled={!steers()} onclick={() => void sketch(d, t)}>
{!t.mockup_png ? 'Have the scout draw it' : remarks.length ? `Draw it again with ${remarks.length === 1 ? 'the remark' : `${remarks.length} remarks`}` : 'Draw it again'}
</button>
)
// 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 ? <del class="tree-edit__was">{e.was}</del> : null,
e.was ? ' ' : null,
<ins class="tree-edit__now">{now}</ins>,
<button type="button" class="tree-edit__undo" disabled={!steers()} title={`Changed by ${e.by}`} onclick={() => void treeOp('undone', 'tech_edit', {id: t.id, [k]: e.was}, true).then((out) => {
const back = out?.techs.find((x) => x.id === t.id)?.edited?.[k]
if (back) state.undone[`${t.id}:${k}`] = back.at
})}>
Undo
</button>,
]
}
// The person's remarks on the mockup, for its next drawing.
const remarkList = remarks.length ? (
<ol class="tree-remarks">
{remarks.map((r) => (
<li>
<span>{r.text}</span>
<button type="button" class="tree-insight__drop" title="Take it back" disabled={!steers()} onclick={() => void treeOp('remark taken back', 'remark_drop', {id: t.id, remark: r.id}, true)}>
×
</button>
</li>
))}
</ol>
) : 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 ? (
<span class="hint">Session {sessionLink(t.photograph.session)} is photographing it…</span>
) : waiting >= 0 ? (
<span class="hint">Waiting its turn to be photographed{waiting ? ` · ${waiting} before it` : ''}</span>
) : t.state === 'built' ? (
<button type="button" class="tree-past" disabled={!steers()} onclick={() => void treeOp('photographing', 'photograph', {id: t.id})}>
{shots.length ? 'Photograph it again' : 'Show how it works now'}
</button>
) : null
const real = shots.length ? (
<figure class="tree-mockup tree-mockup--real">
{shots.map((s) => {
const src = `/v1/hosted/tree/shots/${t.id}/${s.n}`
return (
<div class="tree-real">
<a class="tree-mockup__shot" href={src} target="_blank" rel="noopener" title="Open it at full size">
<img src={src} alt={s.caption || t.name} loading="lazy" />
</a>
<div class="tree-real__caption">
{s.caption ? <span>{s.caption}</span> : null}
<button type="button" class="tree-insight__drop" title="Take this picture off" disabled={!steers()} onclick={() => void treeOp('picture taken off', 'shot_drop', {id: t.id, n: s.n}, true)}>
×
</button>
</div>
</div>
)
})}
<figcaption>
<span class="tree-mockup__what">{t.state === 'built' ? 'As it works now' : 'As its session built it, before it landed'}</span>
{photoNote}
</figcaption>
</figure>
) : t.state === 'built' ? (
<div class="tree-mockup tree-mockup--none">
<span>No pictures yet of how it works.</span>
{photoNote}
</div>
) : 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 ? (
<figure class="tree-mockup tree-mockup--shot">
<a class="tree-mockup__shot" href={shot} target="_blank" rel="noopener" title="Open it at full size">
<img src={shot} alt={`Mockup: ${t.name}`} loading="lazy" />
</a>
<figcaption>
<span class="tree-mockup__what">Where someone would use it · what is new is marked NEW</span>
{drawButton}
</figcaption>
{remarkList}
</figure>
) : t.mockup ? (
<figure class="tree-mockup">
<div class="tree-mockup__frame">{m.trust(t.mockup)}</div>
<figcaption>
<span class="tree-mockup__what">Where someone would use it</span>
<span class="tree-mockup__key tree-mockup__key--new">new</span>
<span class="tree-mockup__key">already there</span>
{drawButton}
</figcaption>
{remarkList}
</figure>
) : going ? (
<div class="tree-mockup tree-mockup--none">
<span>No mockup yet of where someone would use it.</span>
{drawButton}
</div>
) : 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(
<Button variant="ghost" class="tree-detail__aside" onclick={() => (state.dropping = false)}>
Cancel
</Button>,
<Button variant="danger" disabled={!steers()} onclick={() => void treeOp('not this', 'tech_drop', {id: t.id, why: state.dropWhy.trim()}).then(close)}>
Drop it
</Button>,
)
} 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(
<Button variant="secondary" disabled={!steers()} onclick={() => headFor(d, t.id, t.name, close)}>
Head this way
</Button>,
)
}
// Starting a guess keeps it (tree.rs `mark_research`).
if (t.state === 'available' || t.state === 'locked' || t.state === 'fog') {
buttons.push(
<Button variant="primary" disabled={!steers()} onclick={() => void research(t).then(close)}>
Start building
</Button>,
)
}
if (t.state === 'dropped') {
buttons.push(
<Button variant="primary" disabled={!steers()} onclick={() => void treeOp('brought back', 'tech_restore', {id: t.id}).then(close)}>
Bring it back
</Button>,
)
}
}
const title = (
<span class="tree-detail__title">
{iconOf(t, 'tree-icon tree-icon--big')}
<span>{field('name', t.name)}</span>
</span>
)
return (
<Dialog model={open} title={title} size="lg" footer={buttons}>
<div class="tree-detail">
{state.talkOpened && talking() ? (
<p class="tree-detail__talk">
<i />
Opened in the conversation: what you say about it changes it here
</p>
) : null}
{t.what ? <p class="tree-detail__what">{field('what', t.what)}</p> : null}
{/* The real thing comes first, right under what it is: what it looks like is the description. */}
{real}
<div class={`tree-detail__split${picture && !wide ? '' : ' tree-detail__split--one'}`}>
<div class="tree-detail__main">
<div class={`tree-status tree-status--${t.state}`}>
<div class="tree-status__title">{STATUS_TITLE[t.state]}</div>
<p>{statusText(d, t, sessionLink)}</p>
{t.sessions?.length || !t.built ? (
<p class="hint tree-status__size">
{techPips(t)}
{t.built ? null : <span>{SIZE_WORD[t.size]}</span>}
{/* The session at work is named in the sentence above; here the ones before it. */}
{earlier.length ? <span class="tree-detail__sessions">sessions {earlier.map((s) => sessionLink(s.id))}</span> : null}
</p>
) : null}
</div>
{t.who || t.differently || (t.exists && !t.built) ? (
<section>
<h3 class="tree-detail__label">What changes</h3>
<dl class="tree-facts">
{t.who ? [<dt>For whom</dt>, <dd>{field('who', t.who)}</dd>] : null}
{t.differently ? [<dt>What they do</dt>, <dd>{field('differently', t.differently)}</dd>] : null}
{t.exists && !t.built ? [<dt>Already there</dt>, <dd>{field('exists', t.exists)}</dd>] : null}
</dl>
</section>
) : null}
{t.built ? null : (
<section>
<h3 class="tree-detail__label">Done when</h3>
<p class="tree-done">
{t.done ? field('done', t.done) : <span class="hint">Not said yet: the session that builds it says it before it asks to land.</span>}{' '}
<Button variant="ghost" disabled={!steers()} onclick={() => editDone(t)}>
{t.done ? 'Change' : 'Say it'}
</Button>
</p>
</section>
)}
<section>
<h3 class="tree-detail__label">Where it sits</h3>
<div class="tree-chain">
{needs.length ? needs.map(node) : <div class="tree-node tree-node--none">Needs nothing first: it can stand on its own</div>}
<div class="tree-chain__arrow">↓</div>
<div class="tree-node tree-node--this">
{iconOf(t)}
<span>{t.name}</span>
</div>
<div class="tree-chain__arrow">↓</div>
{next.length ? next.map(node) : <div class="tree-node tree-node--none">{goal ? `Leads to the goal itself: ${goal.name}` : 'Leads to the goal itself'}</div>}
</div>
</section>
{caveats.length ? (
<section>
<h3 class="tree-detail__label">On record about it{t.built ? ': built, but' : ''}</h3>
{caveats.map((i) => (
<div class="tree-insight tree-insight--caveat">
<div>{i.text}</div>
{i.evidence.length ? <div class="hint">{i.evidence.slice(0, 2).join(' · ')}</div> : null}
<button type="button" class="tree-insight__drop" title="Not this" disabled={!steers()} onclick={() => void treeOp('dropped', 'insight_drop', {id: i.id}, true)}>
×
</button>
</div>
))}
</section>
) : null}
</div>
{picture}
</div>
{pickedGoal(d) && t.state !== 'dropped' ? askScout(d, pickedGoal(d)!, t) : null}
<details class="tree-detail__more">
<summary>
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` : ''}
</summary>
{t.evidence.length ? (
<ul class="tree-evidence">
{t.evidence.map((e) => (
<li>{e}</li>
))}
</ul>
) : (
<p class="hint">No evidence on record.</p>
)}
</details>
{state.dropping ? (
<div class="tree-detail__drop" oncreate={(v: m.VnodeDOM) => (v.dom as HTMLElement).querySelector('input')?.focus()}>
<FieldText model={bind(state, 'dropWhy')} label="Why not this?" placeholder="e.g. not for communities (optional)" />
<span class="hint">The scout will not bring it back.</span>
</div>
) : null}
</div>
</Dialog>
)
}
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 (
<Card class="tree-fold-card">
<div class="tree-next__fold">
<b class="tree-board__title">Notes</b>
<span class="hint">
{live.length ? `${live.length} on this goal${yours.length ? `, ${yours.length} yours` : ''}` : 'None yet'}
{elsewhere ? ` · ${elsewhere} on single techs (⚑)` : ''}
</span>
<Button variant="ghost" aria-expanded={false} onclick={() => (state.notesOpen = true)}>
{live.length ? 'Open ▾' : 'Add one ▾'}
</Button>
</div>
</Card>
)
}
return (
<Card
class="tree-fold-card tree-fold-card--open"
title={`Notes${live.length ? ` · ${live.length}` : ''}`}
actions={
<Button variant="ghost" aria-expanded={true} onclick={() => (state.notesOpen = false)}>
Fold ▴
</Button>
}
>
<div class="tree-idea">
<FieldText model={bind(state, 'idea')} placeholder="Add an idea for this goal…" disabled={!steers()} />
<Button variant="primary" disabled={!steers() || !state.idea.trim()} onclick={() => void send()}>
Add
</Button>
</div>
{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 ? (
<div class="tree-notes">
{list.map((i) => {
const open = state.openNote === i.id
return (
<div class={`tree-note${open ? ' tree-note--open' : ''}`}>
<span class={`tree-note__who tree-note__who--${i.move === 'person' ? 'you' : 'scout'}`}>{i.move === 'person' ? 'you' : 'scout'}</span>
<button type="button" class="tree-note__body" onclick={() => (state.openNote = open ? '' : i.id)}>
<span class="tree-note__text">{i.text}</span>
<span class="hint" title="A note nothing confirms for 30 days fades">
{age(i.at)}
{about(i) ? ` · about ${about(i)}` : ''}
{i.evidence.length && !open ? ` · ${i.evidence.length} ${i.evidence.length === 1 ? 'source' : 'sources'}` : ''}
</span>
</button>
<button type="button" class="tree-insight__drop" title="Not this" disabled={!steers()} onclick={() => void treeOp('dropped', 'insight_drop', {id: i.id}, true)}>
×
</button>
{open && i.evidence.length ? (
<ul class="tree-evidence tree-note__sources">
{i.evidence.map((e) => (
<li>{e}</li>
))}
</ul>
) : null}
</div>
)
})}
</div>
) : (
<p class="hint">None yet.</p>
)}
{shown.length > 5 ? (
<button type="button" class="tree-past" onclick={() => (state.allNotes = !state.allNotes)}>
{state.allNotes ? 'Fewer' : `Show ${shown.length - 5} more`}
</button>
) : null}
{elsewhere ? <p class="hint">+ {elsewhere} on single techs, shown with ⚑ on the tree</p> : null}
</Card>
)
}
// ── A goal's own page ───────────────────────────────────────────────────────
const editing = local({id: '', loaded: '', name: '', statement: '', who: '', signs: '', never: [] as string[], parent: '', repos: {} as Record<string, boolean>, 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: <p>The goal goes, and the techs that lead only to it and are not built.</p>, 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 (
<div class="stack">
<p class="hint">
<a href="/research" class="home__link">
← Research
</a>
</p>
<Card title={g ? g.name : 'New goal'} subtitle={above ? `under “${above.name}”` : 'A sentence of yours: what the work is for.'}>
<FieldText model={bind(editing, 'name')} label="Goal" placeholder="An open metaverse for communities" />
<FieldTextarea model={bind(editing, 'statement')} label="What it means (optional)" placeholder="a sentence or two" rows={3} autosize />
<div class="tree-scoutstart tree-scoutstart--form">
<div class="tree-scoutstart__head">
<span class="tree-scoutbar__av">{SCOUT_ICON}</span>
<b>Where should the scout look?</b>
</div>
<p class="hint">The scout reads these projects' code, without changing it, and fills the tree in: what is built, what comes next.</p>
{repoChips(editing.repos, (r) => {
editing.picked = true
editing.repos = {...editing.repos, [r]: !editing.repos[r]}
})}
{above && !repos.length ? <small class="hint">None picked: it reads those of “{above.name}”.</small> : null}
</div>
<button type="button" class="tree-more" aria-expanded={editing.more} onclick={() => (editing.more = !editing.more)}>
{editing.more ? '▾' : '▸'} More about the goal <span class="hint">— who notices, signs of progress, never</span>
</button>
{editing.more
? [
<FieldText model={bind(editing, 'who')} label="Who notices" placeholder="a community organiser, a member on their phone" />,
<FieldText model={bind(editing, 'signs')} label="Signs of progress" placeholder="what would visibly be different" />,
<FieldTags model={bind(editing, 'never')} label="Never" placeholder="what it must not lead to, then Enter" />,
]
: null}
<div class="tree-goal__tools">
<Button variant="primary" disabled={!steers() || !editing.name.trim() || editing.sending} onclick={() => void save()}>
{editing.sending ? 'Saving…' : scouts ? (g ? 'Save and send the scout' : 'Make the goal and send the scout') : g ? 'Save' : 'Make the goal'}
</Button>
{g ? (
<Button variant="ghost" disabled={!steers()} onclick={() => void remove()}>
Delete
</Button>
) : null}
</div>
</Card>
</div>
)
}
/** ← → 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 <p class="hint">{state.error || 'Loading the research tree…'}</p>
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 (
<div class="stack">
<div class="tree-bar__row">
{goalProjects(d)}
{directionsLink(d)}
</div>
<Card
title={p ? `Research · ${p}` : 'Research'}
subtitle={p ? `${p} has no goal yet.` : 'A tree of what the work is for, as in Civilization: your goals at the end, the techs on the way, built at the top.'}
>
<p>
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.
</p>
<Button variant="primary" disabled={!steers()} onclick={() => go('research/g/new')}>
New goal
</Button>
</Card>
</div>
)
}
const techs = techsOf(d, g.id, state.showDropped)
const dropped = techsOf(d, g.id, true).length - techsOf(d, g.id).length
return (
<div class="stack">
{goalBar(d, g)}
{directionOf(d, g)?.reached ? null : directionCard(d, directionOf(d, g))}
{treeView(d, g, techs)}
<div class="tree-folds">
{whatNext(d, g, techs)}
{historyCard(techs)}
{notesCard(d, g)}
</div>
{dropped ? (
<p class="hint">
<a href="#" onclick={(e: Event) => {
e.preventDefault()
state.showDropped = !state.showDropped
}}>
{state.showDropped ? 'Hide' : 'Show'} {dropped} you said “not this” to
</a>
</p>
) : null}
{techDialog(d)}
{formDialog()}
</div>
)
}
}