garage44.eu/jeroen/midas

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

.. /web/src/components/discuss.tsx

raw

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 (
        <div class="attach discuss__pictures">
            {talk.pictures.map((p) => (
                <span class="attach__item" title={p.name}>
                    <img src={p.url} alt={p.name} />
                    <button type="button" aria-label={`remove ${p.name}`} onclick={() => dropPicture(p.token)}>
                        ×
                    </button>
                </span>
            ))}
            {ui.adding ? <span class="attach__item hint">…</span> : null}
            <label class={`attach__add${busy ? ' is-disabled' : ''}`} title="Add a picture: a photo of a sketch on paper, a screenshot (or paste one)">
                <input
                    type="file"
                    accept="image/png,image/jpeg,image/gif,image/webp"
                    multiple
                    disabled={busy}
                    onchange={(e: Event) => {
                        const input = e.target as HTMLInputElement
                        for (const f of input.files ?? []) void add(f, f.name || 'picture.jpg', 'a picture')
                        input.value = ''
                    }}
                />
                <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true">
                    <path d="M12 5v14M5 12h14" />
                </svg>
                <span class="sr-only">add a picture</span>
            </label>
            <Button size="sm" variant="ghost" disabled={busy} onclick={() => (ui.sketching = !ui.sketching)}>
                {ui.sketching ? 'Close the sketch' : 'Sketch'}
            </Button>
        </div>
    )
}

/**
 * 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 (
            <div class="sketch">
                <canvas
                    class="sketch__pad"
                    onpointerdown={(e: PointerEvent) => {
                        ;(e.target as HTMLCanvasElement).setPointerCapture(e.pointerId)
                        this.last = this.at(e)
                        this.line({x: this.last.x + 0.01, y: this.last.y})
                        ;(e as unknown as {redraw: boolean}).redraw = false
                    }}
                    onpointermove={(e: PointerEvent) => {
                        ;(e as unknown as {redraw: boolean}).redraw = false
                        if (this.last) this.line(this.at(e))
                    }}
                    onpointerup={(e: PointerEvent) => {
                        ;(e as unknown as {redraw: boolean}).redraw = false
                        this.last = null
                    }}
                    onpointercancel={() => (this.last = null)}
                />
                <div class="sketch__foot">
                    <span class="hint">Draw it; the coach sees it when you show it.</span>
                    <Button size="sm" variant="ghost" onclick={() => this.clear()}>
                        Clear
                    </Button>
                    <Button size="sm" variant="primary" disabled={!steers()} onclick={() => this.show()}>
                        Show it
                    </Button>
                </div>
            </div>
        )
    }
}

const mic = (
    <svg viewBox="0 0 16 16" width="15" height="15" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round">
        <rect x="5.5" y="1.5" width="5" height="8" rx="2.5" />
        <path d="M3 7.5a5 5 0 0 0 10 0M8 12.5V15" />
    </svg>
)

/** 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 (
        <button
            class={`frame__icon frame__discuss${on ? ' is-live' : shown ? ' is-on' : ''}`}
            type="button"
            disabled={!steers()}
            title={label}
            aria-label={label}
            onclick={() => (shown ? show(open) : choose())}
        >
            {mic}
            {on ? <span class={`frame__discuss-dot frame__discuss-dot--${talk.state === 'on' ? talk.activity : 'joining'}`} /> : null}
            <span class="frame__discuss-word">{word}</span>
        </button>
    )
}

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<Persona, string> = {
    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 (
        <div class="discuss__earlier">
            <span class="hint">Earlier conversations</span>
            {list.map((t) => (
                <button
                    type="button"
                    class="discuss__earlier-item"
                    onclick={() => {
                        ui.choosing = false
                        void openTalk(t.id).then(() => show(onopen))
                    }}
                >
                    <strong>{t.title || t.preview || '(nothing said)'}</strong>
                    <span class="hint">
                        {subjectOf(t)} · {age(t.updated) === 'now' ? 'just now' : `${age(t.updated)} ago`} · {t.said} said{t.sent_to ? ` · sent to ${t.sent_to}` : ''}
                    </span>
                </button>
            ))}
        </div>
    )
}

/** Talk on in an ended conversation: it is called again with what was said. */
const carryOnButton = () => (
    <button class="queue__clear" type="button" title="Call again and carry on where it was left" disabled={!steers() || talk.available !== true} onclick={() => void carryOn()}>
        Carry on
    </button>
)

/** 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 (
            <Dialog
                model={bind(ui, 'choosing')}
                title="Discuss"
                footer={[
                    <Button variant="ghost" onclick={() => (ui.choosing = false)}>
                        Cancel
                    </Button>,
                    <Button
                        variant="primary"
                        onclick={() => {
                            ui.choosing = false
                            ui.editing = false
                            void startTalk(about, persona)
                            show(attrs.onstart)
                        }}
                    >
                        Start talking
                    </Button>,
                ]}
            >
                <div class="discuss__choose">
                <FieldSelect label="Talk about" model={bind(ui, 'about')} options={options} />
                {roles.length ? (
                    <FieldSelect
                        label="With"
                        model={{
                            get value() {
                                return persona
                            },
                            set value(p: Persona) {
                                ui.persona = p
                            },
                        }}
                        options={roles}
                    />
                ) : null}
                <FieldSegmented
                    model={voice}
                    options={[
                        {value: 'female', label: "Woman's voice"},
                        {value: 'male', label: "Man's voice"},
                    ]}
                />
                <p class="hint">{hint}</p>
                <p class="hint">It goes on until you end it, or say so ("stop the discussion"). The screen stays on meanwhile. What is said is kept.</p>
                {earlier(attrs.onstart)}
                </div>
            </Dialog>
        )
    }
}

/** 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 (
        <div class={`discuss discuss--panel${talk.activity === 'speaking' ? ' discuss--speaking' : ''}`}>
            <div class="queue__head">
                <span class={`discuss__dot discuss__dot--${talk.state} discuss__dot--${talk.activity}`} />
                <span class="discuss__state">
                    <strong>{aboutLabel(about)}</strong> <span class="hint">{stateWord()}</span>
                </span>
                {talk.state === 'on' ? (
                    <button class="queue__clear" type="button" onclick={() => muteTalk(!talk.muted)}>
                        {talk.muted ? 'Unmute' : 'Mute'}
                    </button>
                ) : null}
                {on ? (
                    [
                        <button class="queue__clear" type="button" title="End this conversation and talk about something else" onclick={choose}>
                            Other subject
                        </button>,
                        <button class="queue__clear" type="button" onclick={endTalk}>
                            End
                        </button>,
                    ]
                ) : (
                    [
                        carryOnButton(),
                        <button
                            class="queue__clear"
                            type="button"
                            title="Start another conversation; this one stays kept, under Earlier conversations"
                            onclick={() => {
                                closeTalk()
                                choose()
                            }}
                        >
                            New
                        </button>,
                        <button class="queue__clear" type="button" onclick={closeTalk}>
                            Close
                        </button>,
                    ]
                )}
            </div>
            {coach ? (
                <div class="discuss__design">
                    <div class="discuss__design-head">
                        <span class="hint">The design{talk.sentTo ? ` — sent to ${talk.sentTo}` : ''}</span>
                        <button class="queue__clear" type="button" onclick={() => (ui.editing = !ui.editing)}>
                            {ui.editing ? 'Done' : 'Edit'}
                        </button>
                    </div>
                    {ui.editing ? (
                        <textarea class="discuss__brief-edit" rows={12} value={talk.brief} oninput={(e: Event) => editBrief((e.target as HTMLTextAreaElement).value)} />
                    ) : talk.brief.trim() ? (
                        <div class="discuss__brief md">{markdown(talk.brief)}</div>
                    ) : (
                        <p class="hint">Nothing settled yet: the coach writes the design here as it takes shape.</p>
                    )}
                    {pictures()}
                    <div class="discuss__design-foot">
                        {talk.sentTo ? (
                            <a href={`/sessions/${talk.sentTo}`}>Open {talk.sentTo}</a>
                        ) : (
                            <Button size="sm" variant="primary" disabled={!steers() || !talk.brief.trim()} onclick={() => void sendBrief().then((r) => 'error' in r && (talk.lines = [...talk.lines, {who: 'note', text: String((r as {error: string}).error)}]))}>
                                {sendLabel}
                            </Button>
                        )}
                    </div>
                </div>
            ) : null}
            {talk.following.length && on ? <p class="hint discuss__following">Following {talk.following.join(', ')}: what they report comes into the conversation.</p> : null}
            <div class="discuss__lines" oncreate={stickDown} onupdate={stickDown}>
                {talk.lines.map((l) => (
                    <div class={`discuss__line discuss__line--${l.who}`}>{l.who === 'note' ? <span class="hint">{l.text}</span> : l.text}</div>
                ))}
            </div>
        </div>
    )
}

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 (
            <div class="design">
                <p class="hint">No design in progress. The microphone starts one: "A new session", with the coach.</p>
            </div>
        )
    }
    const about = talk.about!
    const sendLabel = about.kind === 'session' ? `Send to ${about.id}` : 'Start the session'
    return (
        <div class="design" onpaste={pasteInto}>
            <div class="design__head">
                <span class="hint">
                    {aboutLabel(about)} · {stateWord()}
                    {talk.sentTo ? ` · sent to ${talk.sentTo}` : ''}
                </span>
                <span class="design__actions">
                    {/* The call's own controls, here too: on a phone the panel that has them is closed. */}
                    {talk.state === 'on' ? (
                        <Button size="sm" variant="ghost" onclick={() => muteTalk(!talk.muted)}>
                            {talk.muted ? 'Unmute' : 'Mute'}
                        </Button>
                    ) : null}
                    {talking() ? (
                        <Button size="sm" variant="ghost" onclick={endTalk}>
                            End
                        </Button>
                    ) : (
                        [
                            <Button size="sm" variant="ghost" title="Call again and carry on where it was left" disabled={!steers() || talk.available !== true} onclick={() => void carryOn()}>
                                Carry on
                            </Button>,
                            <Button size="sm" variant="ghost" title="Off the page; kept, under Earlier conversations" onclick={closeTalk}>
                                Close
                            </Button>,
                        ]
                    )}
                    <Button size="sm" variant="ghost" onclick={() => (ui.editing = !ui.editing)}>
                        {ui.editing ? 'Done' : 'Edit'}
                    </Button>
                    {talk.sentTo ? (
                        <Button size="sm" variant="secondary" onclick={() => go(`sessions/${talk.sentTo}`)}>
                            Open {talk.sentTo}
                        </Button>
                    ) : (
                        <Button size="sm" variant="primary" disabled={!steers() || !talk.brief.trim()} onclick={() => void sendBrief().then((r) => 'error' in r && (talk.lines = [...talk.lines, {who: 'note', text: String((r as {error: string}).error)}]))}>
                            {sendLabel}
                        </Button>
                    )}
                </span>
            </div>
            {pictures()}
            {ui.sketching ? <SketchPad /> : null}
            {ui.editing ? (
                <textarea class="discuss__brief-edit design__edit" rows={24} value={talk.brief} oninput={(e: Event) => editBrief((e.target as HTMLTextAreaElement).value)} />
            ) : talk.brief.trim() ? (
                <div class="design__paper md">{markdown(talk.brief)}</div>
            ) : (
                <p class="hint design__paper">Nothing settled yet: the coach writes the design here as you talk it through.</p>
            )}
        </div>
    )
}