garage44.eu/jeroen/midas

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

.. /web/src/components/focus.tsx

raw

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

import {plane} from '@/components/autopilot'
import {askConfirm} from '@/components/confirm'
import {openDecision} from '@/components/decisions'
import {QuestionCard} from '@/components/sessions'
import {act} from '@/lib/actions'
import {api} from '@/lib/api'
import {age} from '@/lib/format'
import {answerWords, capShare, focus, focusApi, loadFocus, parseBlocks, ruleFromQuestion} from '@/lib/focus'
import type {Focus, FocusDay, PilotAnswer, Rule} from '@/lib/focus'
import {bind, local} from '@/lib/reactive'
import {go, here} from '@/lib/route'
import {$s, steers} from '@/lib/store'
import {hosted} from '@/lib/stream'
import type {Hosted, LogItem} from '@/lib/stream'

/**
 * Focus (focus.rs): how much deciding the person did today, against the cap
 * they set; the questions held for their next decision block, one at a time;
 * what the autopilot answered for them, with what can still be taken back and
 * the rules it proposes; their week; and the limits themselves.
 */

const clock = (t: number | null | undefined) => (t ? new Date(t * 1000).toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'}) : '')

/** The meter's colour: calm, near the cap, past it. */
function tone(share: number | null): 'ok' | 'near' | 'over' {
    if (share == null || share < 0.8) return 'ok'
    return share < 1 ? 'near' : 'over'
}

function meter(f: Focus): m.Children {
    const share = capShare(f)
    const width = share == null ? Math.min(100, f.today.points * 2.5) : Math.min(100, share * 100)
    return (
        <div class={`focus-meter focus-meter--${tone(share)}`}>
            <div class="focus-meter__fill" style={{width: `${width}%`}} />
        </div>
    )
}

/** What made today's points: decisions, switches, interruptions. */
function breakdown(d: FocusDay): string {
    const parts = [`${d.decisions} decision${d.decisions === 1 ? '' : 's'}`, `${d.switches} switch${d.switches === 1 ? '' : 'es'}`, `${d.interruptions} interruption${d.interruptions === 1 ? '' : 's'}`]
    return parts.join(' · ')
}

/** Whether there is anything to show yet: the person set a limit, or decided something, or the autopilot did. */
const anything = (f: Focus) => !!(f.settings.cap_points || f.settings.blocks.length || f.today.decisions || f.pilot.length || f.rules.length)

// ── On Home ─────────────────────────────────────────────────────────────────

/** Home's line about the person's load: points against their cap, what is held, what the autopilot did. */
export function focusCard(): m.Children {
    void loadFocus(60_000)
    const f = focus.data
    if (!f || !steers() || !anything(f)) return null
    const share = capShare(f)
    return (
        <a class="focus-card" href="/focus">
            <div class="focus-card__top">
                <span class="focus-card__label">Your decisions today</span>
                {share != null ? <Badge tone={tone(share) === 'ok' ? 'neutral' : tone(share) === 'near' ? 'warning' : 'danger'}>{Math.round(share * 100)}% of your cap</Badge> : null}
            </div>
            <div class="focus-card__num">
                <b>{f.today.points}</b>
                <span class="hint">{f.settings.cap_points ? ` of ${f.settings.cap_points} points` : ' points'}</span>
            </div>
            {meter(f)}
            <div class="hint">
                {breakdown(f.today)}
                {f.held && f.holding ? ` · ${f.held} held${f.next_block ? ` for ${clock(f.next_block)}` : ''}` : ''}
                {f.pilot.length ? ` · autopilot answered ${f.pilot.length}` : ''}
            </div>
        </a>
    )
}

/** Before a new session: a word when the person is at their cap, or has as many at work as they wanted. */
export async function startGuard(): Promise<boolean> {
    await loadFocus(5_000)
    const f = focus.data
    if (!f) return true
    const capS = f.settings.cap_sessions
    const busy = capS != null && f.at_work >= capS
    if (!f.today.at_cap && !busy) return true
    const why = f.today.at_cap
        ? `You are at the daily cap you set: ${f.today.points} of ${f.settings.cap_points} points.`
        : `${f.at_work} sessions are at work, and you set ${capS} at once.`
    return askConfirm({title: 'Start another session?', text: <p>{why} A new session brings its own questions.</p>, yes: 'Start anyway'})
}

// ── Today ───────────────────────────────────────────────────────────────────

function today(f: Focus): m.Children {
    const d = f.today
    const share = capShare(f)
    return (
        <Card title="Today">
            <div class="focus-card__num">
                <b>{d.points}</b>
                <span class="hint">{f.settings.cap_points ? ` of ${f.settings.cap_points} points` : ' points (no cap set)'}</span>
                {share != null ? <Badge tone={tone(share) === 'ok' ? 'neutral' : tone(share) === 'near' ? 'warning' : 'danger'}>{Math.round(share * 100)}%</Badge> : null}
            </div>
            {f.settings.cap_points ? meter(f) : null}
            <div class="hint">{breakdown(d)}</div>
            {d.near_cap ? (
                <p class="focus-note">
                    {d.at_cap
                        ? 'At your cap: only what cannot wait reaches your phone, and scheduled runs wait for tomorrow.'
                        : 'Near your cap: only what cannot wait reaches your phone, and the autopilot settles more itself.'}
                </p>
            ) : f.holding ? (
                <p class="focus-note">{f.quiet ? 'Quiet hours: only what cannot wait reaches your phone.' : `Holding what can wait${f.next_block ? ` until your ${clock(f.next_block)} block` : ''}.`}</p>
            ) : null}
            <div class="focus-actions">
                <Button variant="primary" onclick={() => go('focus/block')}>
                    {asking() ? `Start a decision block · ${asking()} waiting` : 'Open a decision block'}
                </Button>
            </div>
            <details class="focus-explain">
                <summary class="hint">How points are counted</summary>
                <p class="hint">
                    A decision is a point; an interruption, a switch from another session, a long read, a landing or a late hour adds one, and an
                    answer in your own words two. It estimates effort; how the day felt is yours to say in Week.
                </p>
            </details>
        </Card>
    )
}

// ── The decision block ──────────────────────────────────────────────────────

/** One thing that waits: a board decision, or a session's open question or request. */
type Waiting = {key: string; kind: 'decision'; decision: (typeof $s.decisions)[number]} | {key: string; kind: 'session'; s: Hosted; it: LogItem | null}

const block = local({logs: {} as Record<string, LogItem[]>, loading: {} as Record<string, boolean>, skipped: [] as string[], done: 0})

/** The question or request a session waits on, from its log. */
function openAsk(items: LogItem[]): LogItem | null {
    for (let i = items.length - 1; i >= 0; i--) {
        const it = items[i]!
        if (it.kind !== 'question' && it.kind !== 'permission') continue
        const answered = items.slice(i + 1).some((a) => (a.kind === 'answered' || a.kind === 'permission_answered') && a.request === it.request)
        return answered ? null : it
    }
    return null
}

const openDecisions = () => $s.decisions.filter((d) => d.answer == null)
const askingSessions = () => hosted().filter((h) => h.status === 'needs_permission' && !h.archived)

/**
 * How many a block would show now. Not the hub's `held`: that counts every
 * push it holds back, news of a landing or a failed deploy too, which a block
 * has no question for.
 */
const asking = () => openDecisions().length + askingSessions().length

function waiting(): Waiting[] {
    const out: Waiting[] = openDecisions().map((d) => ({key: `d:${d.id}`, kind: 'decision' as const, decision: d}))
    const sessions = askingSessions()
    // A session that asks nothing now is read again when it next asks: its old log would show the old question.
    for (const id of Object.keys(block.logs)) {
        if (!sessions.some((h) => h.id === id)) delete block.logs[id]
    }
    for (const s of sessions) {
        if (!block.logs[s.id] && !block.loading[s.id]) {
            block.loading = {...block.loading, [s.id]: true}
            void api
                .sessionLog(s.id)
                .then((r) => (block.logs = {...block.logs, [s.id]: r.items}))
                .finally(() => (block.loading = {...block.loading, [s.id]: false}))
        }
        const it = block.logs[s.id] ? openAsk(block.logs[s.id]!) : null
        out.push({key: `s:${s.id}`, kind: 'session', s, it})
    }
    // Put off ("Later") to the end, in the order put off.
    return [...out.filter((w) => !block.skipped.includes(w.key)), ...block.skipped.map((k) => out.find((w) => w.key === k)).filter((w): w is Waiting => !!w)]
}

function permissionCard(s: Hosted, it: LogItem): m.Children {
    return (
        <div class="msg__permission">
            <div class="q__asks">It asks permission</div>
            <div class="q__text">{it.title}</div>
            <div class="msg__choices">
                {(it.options ?? [])
                    .filter((o) => o.kind !== 'allow_always')
                    .map((o) => (
                        <Button size="sm" variant={o.kind.startsWith('allow') ? 'primary' : 'ghost'} disabled={!steers()} onclick={() => act('answered', () => api.permit(s.id, it.request!, o.optionId))}>
                            {o.name}
                        </Button>
                    ))}
            </div>
        </div>
    )
}

class Block extends MithrilComponent {
    oninit() {
        block.logs = {}
        block.skipped = []
        block.done = 0
        for (const k of Object.keys(seen)) delete seen[k]
    }

    view() {
        const list = waiting()
        const f = focus.data
        const total = list.length + block.done
        if (!list.length) {
            return (
                <div class="focus-block">
                    <Card title="Nothing waits">
                        <p>{block.done ? `You answered ${block.done} in this block.` : 'No question is waiting for you.'}</p>
                        <Button onclick={() => go('focus')}>Back to Steer</Button>
                    </Card>
                </div>
            )
        }
        const w = list[0]!
        const later = () => (block.skipped = [...block.skipped.filter((k) => k !== w.key), w.key])
        let body: m.Children
        let question = ''
        if (w.kind === 'decision') {
            body = openDecision(w.decision)
            question = w.decision.question
        } else if (!w.it) {
            body = <p class="hint">{block.loading[w.s.id] ? 'Reading the session…' : 'Its question is in the session.'}</p>
        } else if (w.it.kind === 'permission') {
            body = permissionCard(w.s, w.it)
            question = w.it.title ?? ''
        } else {
            // Keyed, so the next question gets a card of its own rather than this one's picks; alone in
            // its fragment, as Mithril wants keyed and unkeyed siblings apart.
            body = [m(QuestionCard, {key: w.key, s: w.s, it: w.it, open: true})]
            question = w.it.message ?? ''
        }
        return (
            <div class="focus-block">
                <div class="focus-block__top">
                    <span class="hint">
                        Decision block · {block.done + 1} of {total}
                    </span>
                    <Button size="sm" variant="ghost" onclick={() => go('focus')}>
                        End block
                    </Button>
                </div>
                <div class="focus-meter focus-meter--thin">
                    <div class="focus-meter__fill" style={{width: `${(block.done / Math.max(1, total)) * 100}%`}} />
                </div>
                {w.kind === 'session' ? (
                    <div class="focus-block__who">
                        <a href={`/sessions/${w.s.id}`}>{w.s.title}</a>
                        {w.it ? <span class="hint"> · asked {age(w.it.at)} ago</span> : null}
                        {w.s.autopilot?.on && w.s.autopilot.state === 'left' ? <div class="hint">{plane(12)} the autopilot left this to you: {w.s.autopilot.left_why}</div> : null}
                    </div>
                ) : null}
                {body}
                <div class="focus-block__foot">
                    <Button variant="ghost" onclick={later}>
                        Later
                    </Button>
                    {question && f ? (
                        <Button
                            variant="ghost"
                            disabled={!steers()}
                            title="the autopilot answers questions like this by itself from now on, with the recommended option"
                            onclick={() => act('rule added', () => focusApi.rule('add', {text: ruleFromQuestion(question), session: w.kind === 'session' ? w.s.id : undefined}).then(() => loadFocus()))}
                        >
                            {plane(13)} Let the autopilot answer these
                        </Button>
                    ) : null}
                </div>
            </div>
        )
    }

    onupdate() {
        // Answered: the session asks nothing any more, so it left the list; count it.
        const keys = new Set(waiting().map((w) => w.key))
        for (const k of Object.keys(seen)) {
            if (!keys.has(k) && !seen[k]) {
                seen[k] = true
                block.done += 1
            }
        }
        for (const k of keys) if (!(k in seen)) seen[k] = false
    }
}

/** The keys a block has shown, and whether each has gone (answered). */
const seen: Record<string, boolean> = {}

// ── The digest ──────────────────────────────────────────────────────────────

const BASIS: Record<string, string> = {rule: 'rule', precedent: 'as before', judgement: 'judgement'}

function pilotRow(a: PilotAnswer, f: Focus): m.Children {
    const undoable = !a.undone && a.kind !== 'message' && f.now < a.undo_until && (a.basis !== 'rule' || a.sure === false)
    // One line each: the session, and what was answered; the question and the reasoning open on a tap.
    return (
        <div class="focus-pilot">
            <div class="focus-pilot__top">
                <a class="sess" href={`/sessions/${a.session}`}>
                    {hosted().find((h) => h.id === a.session)?.title ?? a.session}
                </a>
                {a.undone ? <Badge tone="warning">taken back</Badge> : null}
            </div>
            <details class="focus-pilot__why">
                <summary>
                    <b>{answerWords(a.answer) || '(answered)'}</b>
                    <span class="hint">
                        {' · '}
                        {clock(a.at)}
                        {a.basis ? ` · ${BASIS[a.basis]}` : ''}
                    </span>
                </summary>
                {a.question ? <p class="hint">{a.question}</p> : null}
                {a.why ? <p class="hint">{a.why}</p> : null}
            </details>
            {undoable ? (
                <Button
                    size="sm"
                    variant="ghost"
                    disabled={!steers()}
                    title="the session is told at once to stop acting on this answer and ask you again"
                    onclick={() => act('taken back; the session will ask you again', () => focusApi.undo(a.session, a.n).then(() => loadFocus()))}
                >
                    Take back and ask me · {Math.max(1, Math.round((a.undo_until - f.now) / 60))} min left
                </Button>
            ) : null}
        </div>
    )
}

function ruleRow(r: Rule): m.Children {
    return (
        <div class="focus-rule">
            <div>
                <b>{r.text}</b>
            </div>
            {r.evidence ? <div class="hint">{r.evidence}</div> : null}
            <div class="focus-actions">
                <Button size="sm" variant="primary" disabled={!steers()} onclick={() => act('rule approved', () => focusApi.rule('approve', {id: r.id}).then(() => loadFocus()))}>
                    Approve
                </Button>
                <Button size="sm" variant="ghost" disabled={!steers()} onclick={() => act('kept as yours', () => focusApi.rule('reject', {id: r.id}).then(() => loadFocus()))}>
                    Always ask me
                </Button>
            </div>
        </div>
    )
}

function digest(f: Focus): m.Children {
    const suggested = f.rules.filter((r) => r.state === 'suggested')
    if (!f.pilot.length && !suggested.length) return null
    return (
        <Card title="Autopilot today" subtitle={f.pilot.length ? `${f.pilot.length} answered for you, about ${f.saved} points you did not spend` : undefined}>
            {suggested.length ? (
                <div class="focus-group">
                    <div class="pilot-group">Rules it proposes from your answers</div>
                    {suggested.map(ruleRow)}
                </div>
            ) : null}
            {f.pilot.map((a) => pilotRow(a, f))}
        </Card>
    )
}

// ── The week ────────────────────────────────────────────────────────────────

const FEEL = ['fresh', '', '', '', 'fried']

function week(f: Focus): m.Children {
    const cap = f.settings.cap_points
    const top = Math.max(cap ?? 0, ...f.week.map((d) => d.points), 1) * 1.15
    const heaviest = [...f.week].sort((a, b) => b.points - a.points)[0]
    const day = (d: FocusDay) => new Date(`${d.date}T12:00:00`).toLocaleDateString([], {weekday: 'short'})
    return (
        <Card title="Your week" subtitle={cap ? `Points a day; the line is your cap of ${cap}` : 'Points a day'}>
            <div class="focus-bars">
                {cap ? <div class="focus-bars__cap" style={{bottom: `${(cap / top) * 100}%`}} /> : null}
                {f.week.map((d) => (
                    <div class="focus-bars__col" title={`${d.date}: ${d.points} points, ${breakdown(d)}${d.checkin ? `, felt ${d.checkin}/5` : ''}`}>
                        <div class={`focus-bars__bar focus-bars__bar--${tone(cap ? d.points / cap : null)}`} style={{height: `${(d.points / top) * 100}%`}} />
                        <span class="focus-bars__day">{day(d)}</span>
                        <span class="focus-bars__feel">{d.checkin ? `${d.checkin}/5` : ''}</span>
                    </div>
                ))}
            </div>
            {heaviest && heaviest.points ? (
                <div class="focus-heavy">
                    <div class="pilot-group">What made {day(heaviest)} heaviest</div>
                    <dl>
                        <dt>Decisions</dt>
                        <dd>{heaviest.decisions}</dd>
                        <dt>Switches between sessions</dt>
                        <dd>{heaviest.switches}</dd>
                        <dt>Answered within 3 min of being asked</dt>
                        <dd>{heaviest.interruptions}</dd>
                        <dt>Your own words</dt>
                        <dd>{heaviest.own_words}</dd>
                        <dt>Landings</dt>
                        <dd>{heaviest.landings}</dd>
                        <dt>In quiet hours</dt>
                        <dd>{heaviest.late}</dd>
                        <dt>Most sessions at work at once</dt>
                        <dd>{heaviest.peak}</dd>
                    </dl>
                </div>
            ) : null}
            <div class="focus-group">
                <div class="pilot-group">How did today feel?</div>
                <div class="focus-feel">
                    {[1, 2, 3, 4, 5].map((n) => (
                        <button type="button" class={f.checkin === n ? 'is-on' : ''} disabled={!steers()} onclick={() => act('noted', () => focusApi.checkin(n).then(() => loadFocus()), {quiet: true})}>
                            {n} {FEEL[n - 1]}
                        </button>
                    ))}
                </div>
                {f.suggested_cap ? (
                    <p class="hint">
                        Days that felt fresh averaged {f.suggested_cap.fresh} points, days that felt fried {f.suggested_cap.fried}.{' '}
                        {f.settings.cap_points !== f.suggested_cap.cap ? (
                            <button type="button" class="home__link" disabled={!steers()} onclick={() => act('cap set', () => focusApi.settings({cap_points: f.suggested_cap!.cap}).then(() => loadFocus()))}>
                                Set your cap to {f.suggested_cap.cap}
                            </button>
                        ) : (
                            `Your cap is ${f.suggested_cap.cap}.`
                        )}
                    </p>
                ) : (
                    <p class="hint">One tap at the end of a day. After a few fresh and a few fried days, it suggests a cap.</p>
                )}
            </div>
        </Card>
    )
}

// ── The limits ──────────────────────────────────────────────────────────────

const form = local({
    seeded: false,
    cap: null as number | null,
    capS: null as number | null,
    blocks: [] as string[],
    from: '',
    until: '',
    undo: 30 as number | null,
    rule: '',
})

function seed(f: Focus) {
    if (form.seeded) return
    const s = f.settings
    Object.assign(form, {seeded: true, cap: s.cap_points, capS: s.cap_sessions, blocks: [...s.blocks], from: s.quiet_from ?? '', until: s.quiet_until ?? '', undo: s.undo_min})
}

/** Every half hour of the day, and "off": the quiet hours' choices. */
const HALF_HOURS = [
    {value: '', label: 'off'},
    ...Array.from({length: 48}, (_, i) => {
        const t = `${String(Math.floor(i / 2)).padStart(2, '0')}:${i % 2 ? '30' : '00'}`
        return {value: t, label: t}
    }),
]

/** A switch that saves at once, as the hub has it. */
const switchModel = (f: Focus, k: 'hold' | 'rules_everywhere') => ({
    get value() {
        return f.settings[k]
    },
    set value(v: boolean) {
        void act('saved', () => focusApi.settings({[k]: v}).then(() => loadFocus()), {quiet: true})
    },
})

function limits(f: Focus): m.Children {
    seed(f)
    const s = f.settings
    const save = () =>
        act('limits saved', async () => {
            await focusApi.settings({
                cap_points: form.cap,
                cap_sessions: form.capS,
                blocks: parseBlocks(form.blocks.join(' ')),
                quiet_from: form.from || null,
                quiet_until: form.until || null,
                undo_min: form.undo ?? 30,
            })
            form.seeded = false
            await loadFocus()
        })
    const addRule = () =>
        act('rule added', async () => {
            await focusApi.rule('add', {text: form.rule})
            form.rule = ''
            await loadFocus()
        })
    const badTimes = form.blocks.filter((b) => !parseBlocks(b).length)
    const approved = f.rules.filter((r) => r.state === 'approved')
    return [
        <Card title="Who decides what">
            <ul class="focus-tiers">
                <li>
                    <Badge tone="success">Autopilot</Badge> a rule you approved covers it
                </li>
                <li>
                    <Badge tone="info">Autopilot, you can take it back</Badge> it was not sure, for {s.undo_min} minutes
                </li>
                <li>
                    <Badge tone="warning">Your next block</Badge> new, or it needs your judgement
                </li>
                <li>
                    <Badge tone="danger">Now</Badge> it cannot be undone, or goes outside
                </li>
            </ul>
            <p class="hint">This applies in sessions on autopilot. What cannot be undone and was not asked for is always yours.</p>
            <FieldSwitch
                model={switchModel(f, 'rules_everywhere')}
                disabled={!steers()}
                label="Use my rules in every session"
                help="Also in sessions without the autopilot: a question a rule settles is answered, any other stays yours."
            />
        </Card>,
        <Card title="Decision blocks and quiet hours">
            <FieldTags
                model={bind(form, 'blocks')}
                label="Blocks at"
                placeholder="10:00, then Enter"
                help="Times of day when what waited is put to you at once."
                error={badTimes.length ? `${badTimes.join(', ')}: a time of day is HH:MM` : null}
            />
            <FieldSwitch
                model={switchModel(f, 'hold')}
                disabled={!steers() || !s.blocks.length}
                label="Hold what can wait between blocks"
                help={s.blocks.length ? 'No push for it until the next block; what cannot wait still comes.' : 'Save a block first.'}
            />
            <div class="focus-row">
                <FieldSelect label="Quiet from" model={bind(form, 'from')} options={HALF_HOURS} />
                <FieldSelect label="until" model={bind(form, 'until')} options={HALF_HOURS} />
            </div>
            <FieldNumber label="Take-back window" model={bind(form, 'undo')} min={0} max={1440} step={5} unit="min" help="How long an answer the autopilot was not sure of can be taken back." />
        </Card>,
        <Card title="Your daily cap">
            <div class="focus-row">
                <FieldNumber label="Points a day" model={bind(form, 'cap')} min={1} max={1000} placeholder="no cap" />
                <FieldNumber label="Sessions at work at once" model={bind(form, 'capS')} min={1} max={50} placeholder="no cap" />
            </div>
            <p class="hint">
                Near the cap, the autopilot settles more itself and only what cannot wait reaches your phone. At the cap, scheduled runs wait for
                tomorrow and New session asks first. Every question still shows here.
            </p>
            <Button variant="primary" disabled={!steers() || badTimes.length > 0} onclick={save}>
                Save blocks, quiet hours and cap
            </Button>
        </Card>,
        <Card title={`Rules (${approved.length})`} subtitle="What the autopilot may decide without you, in your words">
            {approved.map((r) => (
                <div class="focus-rule focus-rule--on">
                    <span>{r.text}</span>
                    <span class="hint">{r.uses ? `used ${r.uses}×` : 'not used yet'}</span>
                    <Button size="sm" variant="ghost" disabled={!steers()} onclick={() => act('rule removed', () => focusApi.rule('remove', {id: r.id}).then(() => loadFocus()))}>
                        Remove
                    </Button>
                </div>
            ))}
            <FieldText
                model={bind(form, 'rule')}
                label="A new rule"
                placeholder="e.g. Take a free build node when one is needed"
                suffix={
                    <Button size="sm" variant="ghost" disabled={!steers() || !form.rule.trim()} onclick={addRule}>
                        Add
                    </Button>
                }
            />
        </Card>,
    ]
}

// ── The page ────────────────────────────────────────────────────────────────

/** Which view is open: the address says (`/focus/week`, `/focus/rules`); Steer's tabs go there. */
const view = () => (here() === 'focus/week' ? 'week' : here() === 'focus/rules' ? 'limits' : 'today')

export class FocusPage extends MithrilComponent {
    tick = 0

    oninit() {
        // An old link opened a view by its query: /focus?view=week.
        const v = new URLSearchParams(location.search).get('view')
        if (v === 'week') go('focus/week', {replace: true})
        else if (v === 'limits') go('focus/rules', {replace: true})
        void loadFocus()
        this.tick = window.setInterval(() => void loadFocus(), 30_000)
    }

    onremove() {
        clearInterval(this.tick)
    }

    view() {
        if (here() === 'focus/block') return m(Block)
        const f = focus.data
        if (!f) return <p class="hint">{focus.error ? `Could not read your focus: ${focus.error}` : 'Reading…'}</p>
        return (
            <div class="focus">
                {view() === 'today' ? [today(f), digest(f)] : view() === 'week' ? week(f) : limits(f)}
            </div>
        )
    }
}