Skip to content

An open-source, self-hosted system for apps built with web technologies.

13.6 KB
Raw Blame
import { constrainWindowGeometry, resolveWindowGeometry, type WindowRegion, type ViewSize } from "@client/view/components/window-manager/window-geometry"
import { type PresentationAnimation } from "@client/view/components/desktop-host/presentation"
import { resolvePresentationTransaction } from "@client/view/appearance/motion"
import { type Transaction, type Position, type Size, type PresentationTransaction } from "@phreshos/core"
import { useMotionValue, type MotionStyle } from "motion/react"
import { useEffect, useLayoutEffect, useRef } from "react"
import { WindowGeometryAnimation } from "./window-geometry-animation"
import { timing, useAppearance } from "@phreshos/react-ui"

interface WindowGeometryMotionOptions {
    position: Position
    size: Size
    animation?: PresentationAnimation | null
    transaction?: PresentationTransaction | null
    immediate: boolean
    /** Moves visibly only when the person can see where it starts or where it ends; otherwise it is simply there. */
    seenOnly?: boolean
    minimumSize?: ViewSize
    onComplete?: (revision: number) => void
}

/**
 * One continuous presentation of Window geometry.
 *
 * Core values remain the destination. Motion values exclusively own the
 * visible pixels, including during a pointer gesture, so releasing a drag
 * cannot hand the transform to another renderer before snapping begins.
 */
export default function useWindowGeometryMotion({ position, size, animation, transaction, immediate, seenOnly = false, minimumSize, onComplete }: WindowGeometryMotionOptions) {

    const frame = useRef<HTMLDivElement>(null)
    const x = useMotionValue(typeof position.x === "number" ? position.x : 0)
    const y = useMotionValue(typeof position.y === "number" ? position.y : 0)
    const width = useMotionValue(typeof size.width === "number" ? size.width : 0)
    const height = useMotionValue(typeof size.height === "number" ? size.height : 0)
    const layoutWidth = useMotionValue(width.get())
    const layoutHeight = useMotionValue(height.get())
    const transformOrigin = useMotionValue("0px 0px")
    const scaleX = useMotionValue(1)
    const scaleY = useMotionValue(1)

    // The scale reads the shown size against the laid-out one. It is set the moment either changes,
    // so both reach the screen in the same frame: a derived value would follow a frame later, and the
    // Window would flash once at its laid-out size when a resize starts.
    useEffect(function () {

        const fit = () => {
            scaleX.set(layoutWidth.get() === 0 ? 1 : width.get() / layoutWidth.get())
            scaleY.set(layoutHeight.get() === 0 ? 1 : height.get() / layoutHeight.get())
        }

        fit()

        const stops = [width, height, layoutWidth, layoutHeight].map(value => value.on("change", fit))

        return () => stops.forEach(stop => stop())

    }, [width, height, layoutWidth, layoutHeight, scaleX, scaleY])
    const animator = useRef<WindowGeometryAnimation | null>(null)
    if (!animator.current) animator.current = new WindowGeometryAnimation({ x, y, width, height }, { width: layoutWidth, height: layoutHeight })
    const gesturing = useRef(false)
    const gestureRevision = useRef(0)
    const restoringGesture = useRef(false)
    const initialized = useRef(false)
    const tempo = useAppearance().tempo
    const values = useRef({ position, size, animation, transaction, immediate, tempo, seenOnly, minimumSize, onComplete })

    values.current = { position, size, animation, transaction, immediate, tempo, seenOnly, minimumSize, onComplete }

    function read(): WindowRegion {

        return { x: x.get(), y: y.get(), width: width.get(), height: height.get() }
    }

    /** Hears every step of the box's position: at rest, along a motion, and with the pointer. */
    function watch(listener: () => void) {

        const stopX = x.on("change", listener)
        const stopY = y.on("change", listener)

        return () => {
            stopX()
            stopY()
        }
    }

    function stop() {

        animator.current!.stop()
    }

    function completeGestureRestore() {

        if (!restoringGesture.current) return

        restoringGesture.current = false
        transformOrigin.set("0px 0px")
    }

    function set(region: WindowRegion) {

        animator.current!.set(region)
    }

    function present(region: WindowRegion) {

        stop()
        set(region)
    }

    /**
     * The motion to a place when none was asked for: it comes from how far the box goes, and from
     * whether it leaves the person's sight on the way.
     */
    function timingTo(region: WindowRegion) {

        const from = read()

        return timing("window", { distance: travel(from, region), leaving: seen(from) && !seen(region), tempo: values.current.tempo })
    }

    function transition(region: WindowRegion, transaction: Transaction = timingTo(region), complete?: () => void) {

        if (immediate) {

            set(region)
            complete?.()

            return
        }

        animator.current!.transition(region, transaction, () => {

            completeGestureRestore()
            complete?.()
        })
    }

    function resolve() {

        const parent = frame.current?.parentElement

        if (!parent) return null

        const surface = logicalSize(parent)
        const region = resolveWindowGeometry(values.current.position, values.current.size, surface)
        return values.current.minimumSize ? constrainWindowGeometry(region, surface, values.current.minimumSize) : region
    }

    /** Whether a box on the plane touches the screen. */
    function seen(shown: WindowRegion) {

        const parent = frame.current?.parentElement

        if (!parent) return false

        const surface = logicalSize(parent)

        return shown.x < surface.width && shown.x + shown.width > 0 && shown.y < surface.height && shown.y + shown.height > 0
    }

    /** Whether the person can see where the box is now or where it is going. */
    function seenAtAnEnd(region: WindowRegion) {

        return seen(read()) || seen(region)
    }

    useLayoutEffect(function () {

        const region = resolve()

        if (!region || gesturing.current) return

        const revision = animation?.revision

        if (!initialized.current) {

            initialized.current = true
            set(region)

            if (revision !== undefined) onComplete?.(revision)

            return
        }

        const selected = animation
            ? resolvePresentationTransaction(animation.transaction, timingTo(region))
            : transaction === undefined || transaction === null
                ? null
                : resolvePresentationTransaction(transaction, timingTo(region))

        // A motion shows where something went or where it came from; between two places the person
        // does not see, there is nothing to show, and a path across the screen would only distract.
        if (!selected || (values.current.seenOnly && !seenAtAnEnd(region))) {
            set(region)
            if (revision !== undefined) onComplete?.(revision)
            return
        }

        transition(region, selected, revision === undefined ? undefined : () => onComplete?.(revision))

    }, [position.x, position.y, size.width, size.height, animation?.revision, transaction, immediate, minimumSize?.width, minimumSize?.height])

    useLayoutEffect(function () {

        const parent = frame.current?.parentElement

        if (!parent) return

        let bounds = logicalSize(parent)

        const observer = new ResizeObserver(function () {

            const next = logicalSize(parent)

            if (next.width === bounds.width && next.height === bounds.height) return

            bounds = next

            if (gesturing.current) return

            const region = resolve()

            if (region) {

                set(region)
            }
        })

        observer.observe(parent)

        return () => observer.disconnect()

    }, [])

    useLayoutEffect(() => () => { stopChase(); stop() }, [])

    function beginGesture() {

        const parent = frame.current?.parentElement

        if (!parent) return null

        completeGestureRestore()
        gesturing.current = true
        const revision = ++gestureRevision.current
        stopChase()
        stop()

        const physical = parent.getBoundingClientRect()

        return {
            bounds: { left: physical.left, top: physical.top, ...logicalSize(parent) },
            region: read(),
            revision
        }
    }

    // A dragged box does not jump to each pointer event: it chases the pointer's place each frame,
    // which melts the hand's small jolts and keeps its intent.
    const chase = useRef<{ target: WindowRegion, frame: number, last: number } | null>(null)

    function stopChase() {

        if (chase.current?.frame) cancelAnimationFrame(chase.current.frame)

        chase.current = null
    }

    function follow(time: number) {

        const state = chase.current

        if (!state) return

        const step = state.last ? Math.min(time - state.last, 64) : 16

        state.last = time

        const share = values.current.immediate ? 1 : 1 - Math.exp(-step / 16)

        const shown = read()

        const next = {
            x: shown.x + (state.target.x - shown.x) * share,
            y: shown.y + (state.target.y - shown.y) * share,
            width: shown.width + (state.target.width - shown.width) * share,
            height: shown.height + (state.target.height - shown.height) * share
        }

        if (restoringGesture.current) animator.current!.setPosition(next)

        else set(next)

        const near = Math.abs(state.target.x - next.x) < 0.5 && Math.abs(state.target.y - next.y) < 0.5 && Math.abs(state.target.width - next.width) < 0.5 && Math.abs(state.target.height - next.height) < 0.5

        if (near) {

            if (restoringGesture.current) animator.current!.setPosition(state.target)

            else set(state.target)

            state.frame = 0

            return
        }

        state.frame = requestAnimationFrame(follow)
    }

    function updateGesture(region: WindowRegion) {

        if (!chase.current) chase.current = { target: region, frame: 0, last: 0 }

        chase.current.target = region

        if (!chase.current.frame) chase.current.frame = requestAnimationFrame(follow)
    }

    /**
     * Changes the shown box at once, outside the chase that smooths a hand's motion: for a change
     * the painting makes at the same moment, such as sides letting go of the edges, which must not
     * show between its two states.
     */
    function reshapeGesture(change: (shown: WindowRegion) => WindowRegion) {

        set(change(read()))
    }

    function restoreGesture(region: WindowRegion) {

        // Without animations, it is its restored size at once, as every other change is.
        if (values.current.immediate) {

            set(region)

            return
        }

        const shown = read()
        const scaleX = region.width === 0 ? 1 : shown.width / region.width
        const scaleY = region.height === 0 ? 1 : shown.height / region.height
        const originX = scaleX === 1 ? 0 : (shown.x - region.x) / (1 - scaleX)
        const originY = scaleY === 1 ? 0 : (shown.y - region.y) / (1 - scaleY)

        restoringGesture.current = true
        transformOrigin.set(`${originX}px ${originY}px`)
        animator.current!.transitionSize(region, timing("window", { distance: Math.hypot(region.width - shown.width, region.height - shown.height), tempo: values.current.tempo }), () => {

            completeGestureRestore()
        })
    }

    function targetGesture(revision: number, region: WindowRegion) {

        if (gestureRevision.current !== revision) return false

        stopChase()

        completeGestureRestore()
        transition(region)

        return true
    }

    function settleGesture(revision: number) {

        if (gestureRevision.current !== revision) return false

        stopChase()

        // The authoritative request has now settled. The visible values
        // already express its result, so ownership can change without
        // retargeting Motion through an earlier server snapshot.
        gesturing.current = false

        return true
    }

    function finishGesture(region?: WindowRegion, revision = gestureRevision.current) {

        if (gestureRevision.current !== revision) return false

        stopChase()

        gesturing.current = false

        if (region) {

            completeGestureRestore()
            transition(region)
        }

        return true
    }

    function cancelGesture(revision = gestureRevision.current) {

        if (gestureRevision.current !== revision) return false

        stopChase()

        gesturing.current = false
        completeGestureRestore()

        const region = resolve()

        if (region) {

            set(region)
        }

        return true
    }

    return {
        frame,
        style: { x, y, width: layoutWidth, height: layoutHeight, scaleX, scaleY, transformOrigin } satisfies MotionStyle,
        read,
        watch,
        present,
        beginGesture,
        updateGesture,
        reshapeGesture,
        restoreGesture,
        targetGesture,
        settleGesture,
        finishGesture,
        cancelGesture
    }
}

function logicalSize(element: HTMLElement) {
    return { width: element.clientWidth, height: element.clientHeight }
}

/** How far a box travels between two places: its center's path, and half of how much its size changes. */
function travel(from: WindowRegion, to: WindowRegion) {

    const moved = Math.hypot(to.x + to.width / 2 - from.x - from.width / 2, to.y + to.height / 2 - from.y - from.height / 2)

    return moved + Math.hypot(to.width - from.width, to.height - from.height) / 2
}