import m, {MithrilComponent} from '@garage44/mithril'
import {Button, Dialog, FieldSegmented, FieldSelect} from '@garage44/mithril/components'
import {api} from '@/lib/api'
import type {TalkSummary} from '@/lib/api'
import {aboutLabel, addPicture, carryOn, closeTalk, designs, DESIGNERS, dropPicture, editBrief, endTalk, muteTalk, openTalk, sendBrief, setVoiceOf, startTalk, talk, talking, voiceOf} from '@/lib/discuss'
import type {About, Persona, Voice} from '@/lib/discuss'
import {age} from '@/lib/format'
import {markdown} from '@/lib/markdown'
import {bind, local} from '@/lib/reactive'
import {go, here} from '@/lib/route'
import {$s, steers} from '@/lib/store'
import {hosted} from '@/lib/stream'
/**
* A voice conversation from the header (discuss.ts): the button, the dialog
* that picks what it is about, and the panel beside the page with what was
* said and, with the coach, the design as it stands.
*/
const ui = local({
choosing: false,
/** The dialog's choice: `new`, `board`, `free`, or a session's id. */
about: 'new',
persona: 'coach' as Persona,
editing: false,
/** The sketch pad open on the design's page. */
sketching: false,
/** Pictures on their way up. */
adding: 0,
/** Conversations kept on the hub (talks.rs), newest first: asked each time the dialog opens. */
earlier: [] as TalkSummary[],
})
/** A picture into the conversation: the coach sees it, and it goes with the brief. */
async function add(blob: Blob, name: string, what: string) {
ui.adding++
try {
await addPicture(blob, name, what)
} catch (e) {
talk.lines = [...talk.lines, {who: 'note', text: `${name}: not added (${(e as Error).message})`}]
} finally {
ui.adding--
m.redraw()
}
}
/** The images a paste carries (a screenshot), into the conversation. */
function pasteInto(e: ClipboardEvent) {
const files = [...(e.clipboardData?.items ?? [])].filter((i) => i.kind === 'file' && i.type.startsWith('image/')).map((i) => i.getAsFile()).filter((f): f is File => f != null)
if (!files.length) return
e.preventDefault()
for (const f of files) void add(f, f.name && f.name !== 'image' ? f.name : `pasted.${f.type.split('/')[1] ?? 'png'}`, 'a pasted picture')
}
/**
* The pictures with the design: what the person added (each with a ×), a
* picker (the camera on a phone), and the sketch pad's switch.
*/
function pictures(): m.Children {
if (!talk.about || !designs(talk.persona)) return null
const busy = !steers() || talk.pictures.length >= 5
return (
)
}
/**
* A pad to draw on with a finger or the mouse, for what is quicker drawn than
* said: a layout, a flow, where a button goes. "Show it" hands the drawing to
* the conversation as a picture, and clears the pad for the next.
*/
class SketchPad extends MithrilComponent {
private canvas: HTMLCanvasElement | null = null
private last: {x: number; y: number} | null = null
private drawn = false
oncreate(v: m.VnodeDOM) {
const c = (v.dom as HTMLElement).querySelector('canvas')!
this.canvas = c
const ratio = window.devicePixelRatio || 1
c.width = Math.round(c.clientWidth * ratio)
c.height = Math.round(c.clientHeight * ratio)
const g = c.getContext('2d')!
g.scale(ratio, ratio)
this.clear()
}
private clear() {
const c = this.canvas
if (!c) return
const g = c.getContext('2d')!
g.fillStyle = '#fff'
g.fillRect(0, 0, c.width, c.height)
this.drawn = false
}
private at(e: PointerEvent) {
const r = this.canvas!.getBoundingClientRect()
return {x: e.clientX - r.left, y: e.clientY - r.top}
}
private line(to: {x: number; y: number}) {
const g = this.canvas!.getContext('2d')!
g.strokeStyle = '#111'
g.lineWidth = 2.5
g.lineCap = 'round'
g.lineJoin = 'round'
g.beginPath()
g.moveTo(this.last!.x, this.last!.y)
g.lineTo(to.x, to.y)
g.stroke()
this.last = to
this.drawn = true
}
private show() {
if (!this.drawn) return
this.canvas!.toBlob((b) => {
if (!b) return
void add(b, 'sketch.png', 'a sketch')
this.clear()
}, 'image/png')
}
view() {
return (
)
}
}
const mic = (
)
/** The session the page shows, if it shows one. */
const pageSession = () => here().match(/^sessions\/(s\d+)$/)?.[1] ?? ''
/** What the dialog offers first: what the page is about. */
function preselect() {
const id = pageSession()
if (id) {
ui.about = id
ui.persona = 'midas'
} else if (here() === 'sessions/new') {
ui.about = 'new'
} else if (here() === 'research' || here().startsWith('research/')) {
ui.about = 'tree'
ui.persona = 'midas'
} else {
// Home is the board's page now: what is at work there.
ui.about = $s.tab === 'home' ? 'board' : 'free'
}
}
const aboutOf = (v: string): About => (v === 'new' || v === 'board' || v === 'free' || v === 'tree' ? {kind: v} : {kind: 'session', id: v})
/** Ask what to talk about, from the page it is asked on: to talk about something else than the page. */
function choose() {
preselect()
ui.choosing = true
api.talks()
.then((r) => (ui.earlier = r.talks))
.catch(() => (ui.earlier = []))
}
/** Whether the research page may offer to talk its tree over: the hub can open a conversation, and none is on. */
export const talkAboutTree = () => talk.available === true && !talking()
/** The research page's "Talk it over": the dialog, with the tree already chosen as what to talk about. */
export function openTreeTalk() {
choose()
}
/** Designing goes on a page of its own, where the design has the room; talking, in the panel beside the page. */
export const designing = () => talk.about != null && designs(talk.persona)
/**
* Show the conversation: a design on its page, anything else in the panel
* (`open`). On the design's page already, the panel too: the conversation,
* and its Mute and End, which on a phone are behind this button.
*/
function show(open: () => void) {
if (designing()) go('design')
else open()
}
/**
* The header's button, an icon beside the others: ask what to talk about (the
* page's subject chosen already: a session, designing a new one, everything at
* work on Home), or, while one is on or its design is still shown, open it.
* It asks rather than starting at once, so designing is chosen, never fallen
* into from the new-session page. On a phone it is the
* mic alone; a dot on it says the conversation is on and what it is up to
* (the word is in its label, and in the panel). Only where the hub can open
* one, and for whoever may steer.
*/
export function discussButton(open: () => void): m.Vnode | null {
if (talk.available !== true) return null
const on = talking()
const shown = !!talk.about
const word = on ? stateWord() : shown ? 'Discussion' : 'Discuss'
const label = on ? `Discussion: ${word}` : shown ? 'The last discussion' : 'Discuss: talk it over out loud'
return (
)
}
function stateWord(): string {
if (talk.state === 'joining') return 'Joining…'
if (talk.state === 'reconnecting') return 'Reconnecting…'
if (talk.state === 'off') return 'Ended'
return activityWord()
}
/** What it is up to in a silence: listening, thinking, or busy with something. */
function activityWord(): string {
if (talk.muted && talk.activity === 'listening') return 'Muted'
return talk.activity === 'speaking' ? 'Speaking' : talk.activity === 'working' ? `Busy: ${talk.doing}…` : talk.activity === 'thinking' ? 'Thinking…' : 'Listening'
}
/** What each designing role does, for the dialog. */
const ROLE_HINTS: Record = {
midas: '',
coach: 'The operator: does what you ask in as few turns as it takes.',
designer: 'A design coach: walks through it as its user meets it, and asks about what is unclear.',
executive: 'A CTO / CEO: asks why now, what it costs, what it puts off, and the smallest version worth doing.',
user: 'A customer: reacts as someone who would use it, in plain words.',
}
/** A kept conversation's subject, in the list's words. */
function subjectOf(t: TalkSummary): string {
const a = t.about
if (a.kind === 'session') return `about ${a.id}`
return {new: 'a new session', board: 'the board', tree: 'the research tree', free: 'free'}[a.kind] ?? a.kind
}
/**
* The conversations kept on the hub, the latest first: one opened comes back
* as it was left, with its brief, to read or to carry on.
*/
function earlier(onopen: () => void): m.Children {
const list = ui.earlier.filter((t) => t.id !== talk.id).slice(0, 8)
if (!list.length) return null
return (
Earlier conversations
{list.map((t) => (
))}
)
}
/** Talk on in an ended conversation: it is called again with what was said. */
const carryOnButton = () => (
)
/** What to talk about, and with whom. */
export class DiscussDialog extends MithrilComponent<{onstart: () => void}> {
view({attrs}: m.Vnode<{onstart: () => void}>) {
const sessions = hosted()
.filter((h) => !h.archived && !h.imported && h.status !== 'stopped' && h.status !== 'failed')
.slice(0, 20)
// The page's session, even when it has ended: it can still be talked about.
const here = pageSession()
const listed = here && !sessions.some((h) => h.id === here) ? [...hosted().filter((h) => h.id === here), ...sessions] : sessions
const options = [
{value: 'new', label: 'A new session'},
...listed.map((h) => ({value: h.id, label: `${h.id} · ${h.title}`})),
{value: 'board', label: 'Everything at work'},
{value: 'tree', label: 'The research tree (Goals)'},
{value: 'free', label: 'Nothing in particular'},
]
const about = aboutOf(ui.about)
// A new session is designed, with a role that designs; a session, talked about or designed; the rest, with Midas.
const persona: Persona =
about.kind === 'new' ? (designs(ui.persona) ? ui.persona : 'coach') : about.kind === 'session' ? ui.persona : 'midas'
const roles = about.kind === 'new' ? DESIGNERS : about.kind === 'session' ? [{value: 'midas' as Persona, label: 'Midas'}, ...DESIGNERS] : []
// Each role keeps the voice last picked for it, on this device.
const voice = {
get value(): Voice {
return voiceOf(persona)
},
set value(v: Voice) {
setVoiceOf(persona, v)
},
}
const hint =
persona === 'midas'
? about.kind === 'session'
? 'What it did, how far it is, what it found. Midas sends it something only when you say so.'
: about.kind === 'board'
? 'How the sessions progress and relate, what waits on you, what to do first.'
: about.kind === 'tree'
? 'Design the tree and choose where the research heads. Midas sends the scout out to read the code, and changes the tree only when you say so.'
: 'No session or board: think out loud.'
: `${ROLE_HINTS[persona]} It keeps the design beside the conversation; you check it before ${about.kind === 'session' ? 'it is sent' : 'the session starts'}.`
return (
)
}
}
/** The conversation, beside the page: its state, the design (the coach's, unless its page shows it), what was said. */
export function discussPanel(): m.Children {
if (!talk.about) return null
const on = talking()
const coach = designs(talk.persona) && here() !== 'design'
const about = talk.about
const sendLabel = about.kind === 'session' ? `Send to ${about.id}` : 'Start the session'
return (
The design{talk.sentTo ? ` — sent to ${talk.sentTo}` : ''}
{ui.editing ? (
) : null}
{talk.following.length && on ?
Following {talk.following.join(', ')}: what they report comes into the conversation.
: null}
{talk.lines.map((l) => (
{l.who === 'note' ? {l.text} : l.text}
))}
)
}
const stickDown = (v: m.VnodeDOM) => {
const el = v.dom as HTMLElement
el.scrollTop = el.scrollHeight
}
/**
* Designing with the coach, on a page of its own: the design as it is written,
* with the room a design needs (the conversation is in the panel beside it, or
* behind the header's button on a phone), and what to do with it.
*/
export function DesignPage(): m.Children {
if (!designing()) {
return (
No design in progress. The microphone starts one: "A new session", with the coach.
)
}
const about = talk.about!
const sendLabel = about.kind === 'session' ? `Send to ${about.id}` : 'Start the session'
return (
{aboutLabel(about)} · {stateWord()}
{talk.sentTo ? ` · sent to ${talk.sentTo}` : ''}
{/* The call's own controls, here too: on a phone the panel that has them is closed. */}
{talk.state === 'on' ? (
) : null}
{talking() ? (
) : (
[
,
,
]
)}
{talk.sentTo ? (
) : (
)}