garage44.eu/jeroen/midas

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

.. /web/src/components/fold.tsx

raw

import m from '@garage44/mithril'

import {reduced} from '@/lib/motion'
import {local} from '@/lib/reactive'

/** Whether the message box is folded away on a phone, and how much taller than its two lines it was dragged, kept in this browser. */
const fold = local({shut: read('midas-composer-shut') === '1', grow: Number(read('midas-composer-grow')) || 0})

/** The most the box grows by: half the screen, so the conversation keeps the rest. */
const maxGrow = () => Math.round(window.innerHeight * 0.5)
/** The folded field's height (app.css `.fold__reply`): a box pulled up from folded starts from it. */
const FIELD = 38
/** Dragged this far, it is a drag and not a tap: a finger wobbles more than a mouse. */
const SLOP = 8
/** Dragged down this far past its two lines, it folds away; up this far from folded, it opens. */
const SNAP = 56
/** A flick this fast (px/ms) settles it the way it was thrown, however short. */
const FLING = 0.4
/** How long the box takes to settle once let go, or to open and fold on a tap. */
const SETTLE = 240
const EASE = 'cubic-bezier(0.2, 0.8, 0.2, 1)'

function read(key: string): string | null {
    try {
        return localStorage.getItem(key)
    } catch {
        return null
    }
}

function keep() {
    try {
        localStorage.setItem('midas-composer-shut', fold.shut ? '1' : '0')
        localStorage.setItem('midas-composer-grow', String(fold.grow))
    } catch {
        // A browser that keeps nothing: as it is for this page.
    }
}

const bodyOf = (el: HTMLElement) => el.querySelector<HTMLElement>('.fold__body')

/** The box's body slides open from `from` px to its own height, then is left to size itself. */
function reveal(el: HTMLElement, from: number) {
    const body = bodyOf(el)
    if (!body || reduced()) return
    const to = body.scrollHeight
    if (to <= from) return
    body.animate(
        [
            {maxHeight: `${from}px`, overflow: 'hidden', opacity: from ? 1 : 0.4},
            {maxHeight: `${to}px`, overflow: 'hidden', opacity: 1},
        ],
        {duration: SETTLE, easing: EASE},
    )
}

/**
 * The open box folds, and shrinks from its height (as the finger left it) to the folded
 * pill's. Folded first and then shrunk: the body slid to nothing went all the way down
 * to the page's foot, and the pill then jumped back up out of it.
 */
function collapse(el: HTMLElement) {
    const start = el.offsetHeight
    fold.shut = true
    keep()
    m.redraw.sync()
    unpeek(el)
    if (reduced()) return
    const end = el.offsetHeight
    if (start <= end) return
    el.animate([{height: `${start}px`, overflow: 'hidden'}, {height: `${end}px`, overflow: 'hidden'}], {duration: SETTLE * 0.8, easing: EASE})
    el.querySelector('.fold__shut')?.animate([{opacity: 0}, {opacity: 1}], {duration: SETTLE * 0.8, easing: EASE})
}

/** A body squeezed or peeked by a drag goes back from `from` px to `to`, then is left to size itself. */
function springBack(el: HTMLElement, body: HTMLElement, from: number, to: number) {
    const clear = () => unpeek(el)
    if (reduced() || Math.abs(from - to) < 2) return clear()
    body.animate([{maxHeight: `${from}px`, opacity: body.style.opacity || 1}, {maxHeight: `${to}px`, opacity: 1}], {duration: SETTLE, easing: EASE}).finished.then(clear, clear)
}

/**
 * A tap on the handle or the folded field. Done on the click and not when the finger lifts:
 * opened then, the box was redrawn under the finger before the click came, and the click
 * went to whatever lay there now — the model chip's select, which opened. Opened from the
 * field, the box takes the keyboard, in the tap itself (a phone shows its keyboard only then),
 * with the caret after any draft.
 */
function tapped(e: MouseEvent, write: boolean) {
    const el = (e.currentTarget as HTMLElement).closest('.fold') as HTMLElement
    if (!fold.shut) return collapse(el)
    fold.shut = false
    keep()
    m.redraw.sync()
    reveal(el, FIELD)
    if (!write) return
    const field = el.querySelector<HTMLTextAreaElement>('.fold__body textarea')
    if (!field) return
    field.focus({preventScroll: true})
    const end = field.value.length
    field.setSelectionRange(end, end)
}

/** A drag under way on the bar. */
type Drag = {
    y: number
    grow: number
    moved: boolean
    el: HTMLElement
    /** The open body's height when the drag began: what folding it down squeezes. */
    height: number
    /** Where the finger is now, from where it started (up is negative). */
    dy: number
    /** The last few positions, for how fast it was let go. */
    trail: {t: number; y: number}[]
    frame: number
}
let drag: Drag | null = null
/** When the last drag ended: the click a mouse sends after it is not a tap. A time and not a flag,
 *  since a finger that drags sends no click at all, and a flag left set swallowed the next real tap. */
let draggedAt = 0

/** Past its end the box gives less and less, as a sheet does, rather than stopping dead. */
const rubber = (over: number) => (over <= 0 ? 0 : Math.sqrt(over) * 4)

/** How fast the finger was moving when it lifted, in px/ms (down is positive). */
function velocity(d: Drag): number {
    const now = performance.now()
    // A phone sends a fast flick as one or two moves: the last two are enough then.
    const recent = d.trail.filter((p) => now - p.t < 80)
    if (recent.length < 2) recent.splice(0, recent.length, ...d.trail.slice(-2))
    if (recent.length < 2) return 0
    const a = recent[0]
    const b = recent[recent.length - 1]
    return b.t > a.t ? (b.y - a.y) / (b.t - a.t) : 0
}

/** Where the box would settle with the finger `dy` px from where it started, thrown at `v`. */
function settle(d: Drag, dy: number, v = 0): {shut: boolean; grow: number} {
    if (fold.shut) return dy < -SNAP || (v < -FLING && dy < 0) ? {shut: false, grow: 0} : {shut: true, grow: fold.grow}
    const grow = d.grow - dy
    // Flicked down: a tall box goes back to its two lines, one at its two lines folds away.
    if (grow < -SNAP || (v > FLING && grow < SNAP)) return {shut: true, grow: 0}
    if (v > FLING) return {shut: false, grow: 0}
    return {shut: false, grow: Math.max(0, Math.min(maxGrow(), Math.round(grow)))}
}

function unpeek(el: HTMLElement) {
    el.classList.remove('fold--dragging', 'fold--letgo', 'fold--peek')
    el.style.removeProperty('--fold-grow')
    el.style.removeProperty('--fold-peek')
    const body = bodyOf(el)
    body?.style.removeProperty('max-height')
    body?.style.removeProperty('overflow')
    body?.style.removeProperty('opacity')
}

/** The box under the finger, once a frame: the page itself is not redrawn until the finger lifts. */
function follow() {
    if (!drag) return
    drag.frame = 0
    const {el, dy} = drag
    const body = bodyOf(el)
    el.classList.add('fold--dragging')
    el.classList.toggle('fold--letgo', settle(drag, dy).shut !== fold.shut)
    if (fold.shut) {
        // Folded, the box comes up under the finger as far as it is pulled.
        el.classList.toggle('fold--peek', dy < 0)
        el.style.setProperty('--fold-peek', `${Math.max(0, -dy)}px`)
        return
    }
    const grow = drag.grow - dy
    const max = maxGrow()
    // Up: the box grows with the finger, giving at its limit. Down past its two lines: it is squeezed.
    el.style.setProperty('--fold-grow', `${Math.max(0, Math.min(grow, max) + rubber(grow - max))}px`)
    if (!body) return
    if (grow < 0) {
        const squeezed = Math.max(0, drag.height + grow)
        body.style.maxHeight = `${squeezed}px`
        body.style.overflow = 'hidden'
        body.style.opacity = String(Math.max(0.35, 1 + grow / (drag.height || 1)))
    } else {
        body.style.removeProperty('max-height')
        body.style.removeProperty('overflow')
        body.style.removeProperty('opacity')
    }
}

const handlers = {
    onpointerdown(e: PointerEvent) {
        if (e.button !== 0) return
        const el = (e.currentTarget as HTMLElement).closest('.fold') as HTMLElement
        // A drag let go a moment ago may still be settling: it is finished where it is.
        bodyOf(el)?.getAnimations().forEach((a) => a.finish())
        const now = performance.now()
        drag = {y: e.clientY, grow: fold.grow, moved: false, el, height: bodyOf(el)?.offsetHeight ?? 0, dy: 0, trail: [{t: now, y: e.clientY}], frame: 0}
        ;(e.currentTarget as HTMLElement).setPointerCapture(e.pointerId)
    },
    onpointermove(e: PointerEvent & {redraw?: boolean}) {
        e.redraw = false
        if (!drag) return
        const dy = e.clientY - drag.y
        if (!drag.moved && Math.abs(dy) < SLOP) return
        if (!drag.moved) {
            // Taken up from where the finger is now, so passing the slop is not a jump.
            drag.moved = true
            drag.y += Math.sign(dy) * SLOP
        }
        drag.dy = e.clientY - drag.y
        drag.trail.push({t: performance.now(), y: e.clientY})
        if (drag.trail.length > 8) drag.trail.shift()
        if (!drag.frame) drag.frame = requestAnimationFrame(follow)
    },
    onpointerup(e: PointerEvent) {
        if (!drag) return
        const d = drag
        drag = null
        if (d.frame) cancelAnimationFrame(d.frame)
        // A tap: its click does it (`tapped`).
        if (!d.moved) return unpeek(d.el)
        draggedAt = performance.now()
        d.dy = e.clientY - d.y
        d.trail.push({t: performance.now(), y: e.clientY})
        const to = settle(d, d.dy, velocity(d))
        const body = bodyOf(d.el)
        d.el.classList.remove('fold--dragging', 'fold--letgo')
        if (fold.shut) {
            if (to.shut) {
                // Not pulled far enough: back down into the pill.
                if (body && d.el.classList.contains('fold--peek')) springBack(d.el, body, FIELD + Math.max(0, -d.dy), FIELD)
                else unpeek(d.el)
                return
            }
            // Let go open, it goes on from where the finger left it.
            const peek = FIELD + Math.max(0, -d.dy)
            unpeek(d.el)
            fold.shut = false
            fold.grow = 0
            keep()
            m.redraw.sync()
            reveal(d.el, peek)
            return
        }
        if (to.shut) {
            fold.grow = 0
            collapse(d.el)
            return
        }
        const squeezed = body && d.grow - d.dy < 0 ? body.offsetHeight : 0
        fold.grow = to.grow
        keep()
        // The grow comes to rest by the textarea's own transition (app.css), from where the finger left it; a squeeze springs back.
        m.redraw.sync()
        d.el.style.removeProperty('--fold-grow')
        if (body && squeezed) {
            body.style.removeProperty('max-height')
            const full = body.scrollHeight
            body.style.maxHeight = `${squeezed}px`
            springBack(d.el, body, squeezed, full)
        } else unpeek(d.el)
    },
    onpointercancel() {
        if (!drag) return
        if (drag.frame) cancelAnimationFrame(drag.frame)
        unpeek(drag.el)
        drag = null
    },
}

/**
 * The message box at the page's foot, foldable on a phone so the conversation
 * has the screen to be read. A handle above it, a sheet's: tapped, it folds the
 * box away or brings it back; dragged, the box follows the finger — up for
 * more room to write, down to fold it away, a flick either way enough. On a
 * wider screen it is always open.
 *
 * Folded, it reads as a field to reply in, with the header's buttons (`tools`)
 * beside it: on a phone they leave the header to the session's name and state.
 * Open, it is only for writing, so they are not there.
 */
export function foldable(body: m.Children, o: {draft?: string; tools?: m.Children; hint?: string} = {}): m.Children {
    const draft = o.draft?.trim() ?? ''
    const label = fold.shut ? (draft ? 'Open the message box — a draft is kept' : 'Open the message box') : 'Hide the message box'
    const bar = (cls: string, inner: m.Children, write = false) => (
        <button
            type="button"
            class={cls}
            aria-expanded={!fold.shut}
            aria-label={label}
            title={`${label} — drag to make it taller or fold it away`}
            onclick={(e: MouseEvent) => {
                // A mouse's drag ends in a click too, which the drag has already settled.
                if (performance.now() - draggedAt < 400) return
                tapped(e, write)
            }}
            {...handlers}
        >
            {inner}
        </button>
    )
    return (
        <div class={`fold${fold.shut ? ' fold--shut' : ''}`} style={{'--fold-grow-kept': `${fold.grow}px`}}>
            {bar('fold__bar', <span class="fold__grip" aria-hidden="true" />)}
            {fold.shut ? (
                <div class="fold__shut">
                    {bar(
                        'fold__reply',
                        <span class={`fold__label${draft ? ' fold__label--draft' : ''}`}>
                            {draft ? <span class="fold__draft" aria-hidden="true" /> : null}
                            <span class="fold__text">{draft || o.hint || 'Reply…'}</span>
                        </span>,
                        true,
                    )}
                    {o.tools ? <span class="fold__tools">{o.tools}</span> : null}
                </div>
            ) : null}
            <div class="fold__body">{body}</div>
        </div>
    )
}