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 (
)
}
/** 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 (
)
}
/** 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 {
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:
{d.points}{f.settings.cap_points ? ` of ${f.settings.cap_points} points` : ' points (no cap set)'}
{share != null ? {Math.round(share * 100)}% : null}
{f.settings.cap_points ? meter(f) : null}
{breakdown(d)}
{d.near_cap ? (
{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.'}
) : f.holding ? (
{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` : ''}.`}
) : null}
How points are counted
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.
)
}
// ── 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, loading: {} as Record, 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 (
)
}
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 (
{block.done ? `You answered ${block.done} in this block.` : 'No question is waiting for you.'}
)
}
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 =
{block.loading[w.s.id] ? 'Reading the session…' : 'Its question is in the session.'}
} 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 (
{plane(12)} the autopilot left this to you: {w.s.autopilot.left_why}
: null}
) : null}
{body}
{question && f ? (
) : null}
)
}
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 = {}
// ── The digest ──────────────────────────────────────────────────────────────
const BASIS: Record = {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 (
) : null}
{f.pilot.map((a) => pilotRow(a, f))}
)
}
// ── 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 (
{cap ? : null}
{f.week.map((d) => (
{day(d)}{d.checkin ? `${d.checkin}/5` : ''}
))}
{heaviest && heaviest.points ? (
What made {day(heaviest)} heaviest
Decisions
{heaviest.decisions}
Switches between sessions
{heaviest.switches}
Answered within 3 min of being asked
{heaviest.interruptions}
Your own words
{heaviest.own_words}
Landings
{heaviest.landings}
In quiet hours
{heaviest.late}
Most sessions at work at once
{heaviest.peak}
) : null}
How did today feel?
{[1, 2, 3, 4, 5].map((n) => (
))}
{f.suggested_cap ? (
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 ? (
) : (
`Your cap is ${f.suggested_cap.cap}.`
)}
) : (
One tap at the end of a day. After a few fresh and a few fried days, it suggests a cap.
)}
)
}
// ── 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 [
Autopilot a rule you approved covers it
Autopilot, you can take it back it was not sure, for {s.undo_min} minutes
Your next block new, or it needs your judgement
Now it cannot be undone, or goes outside
This applies in sessions on autopilot. What cannot be undone and was not asked for is always yours.
,
,
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.
,
{approved.map((r) => (
{r.text}{r.uses ? `used ${r.uses}×` : 'not used yet'}
))}
Add
}
/>
,
]
}
// ── 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
{focus.error ? `Could not read your focus: ${focus.error}` : 'Reading…'}