Skip to content

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

6.0 KB
Raw Blame
import { ReactTunnel } from "@the-link/react"
import { useProperty } from "@the-link/react"
import { LinkManagerSnapshot } from "@server/core/link-manager/link-manager"
import LinkManager from "@client/core/link-manager/link-manager"
import { timing, useAppearance } from "@phreshos/react-ui"
import Loading from "../components/loading"
import { DesktopScaleProvider, useDesktopScale } from "./desktop/desktop-scale"
import Alert from "../components/alert"
import { ApplicationContext, LinkManagerContext } from "../contexts"
import usePromise from "@libs/react-promise"
import { useDesktopPreferences } from "../appearance/desktop-preferences"
import { useRememberSystemAppearance } from "../appearance/appearance"
import Authentication from "./authentication/authentication"
import { useCallback, useEffect, useState } from "react"
import Readiness, { useReadiness, useReady } from "@libs/readiness"
import { type DesktopPreferencesUpdate } from "@phreshos/core"
import { cssEasing } from "@phreshos/core"
import {
    connectionRequirement,
    sessionRequirement,
    startupRequirements,
    type DesktopReadinessRequirement,
    wallpaperRequirement
} from "./readiness-requirements"

export default function () {
    const appearance = useAppearance()
    const scale = useDesktopScale()
    const [overlays, setOverlays] = useState<HTMLDivElement | null>(null)

    return <Readiness requirements={startupRequirements}>

        {/* The Desktop and what opens over it, such as a dialog, are one layer: whatever stacks inside it
            stays inside, and the readiness cover stands above all of it. */}
        <div className="relative isolate grid">

            <DesktopScaleProvider scale={scale} container={overlays}>

                <Desktop />

            </DesktopScaleProvider>

            {/* Desktop overlays open here: inside the scale, so they share it, and outside the layout, so
                opening one never takes room from the Desktop. It covers the Desktop, so what opens in it
                has the Desktop's width to lay its text out in, and it catches nothing itself; only what
                opens in it does. */}
            <div ref={setOverlays} className="pointer-events-none absolute inset-0 *:pointer-events-auto" />

        </div>

        <DesktopReadiness appearance={appearance} />

    </Readiness>
}

function DesktopReadiness({ appearance }: { appearance: ReturnType<typeof useAppearance> }) {

    const { pending } = useReadiness<DesktopReadinessRequirement>()

    const covering = pending.length > 0

    const change = timing("change", { tempo: appearance.tempo })

    const duration = change.duration

    // Once faded out, the cover leaves the tree. Kept at zero opacity, it
    // stayed a full-screen layer over the Desktop that repainted with every
    // frame of any animation, and its spinner never stopped.
    const [faded, setFaded] = useState(!covering)

    if (covering && faded) setFaded(false)

    if (!covering && !faded && duration === 0) setFaded(true)

    if (faded) return null

    return <Loading

        aria-hidden={!covering}

        className={covering ? "opacity-100" : "pointer-events-none opacity-0"}

        style={{
            // New pending work must cover the next representation
            // immediately; only completed readiness fades away.
            transitionDuration: covering ? "0ms" : String(duration) + "ms",
            transitionTimingFunction: cssEasing(change.easing),
            transitionProperty: "opacity"
        }}

        onTransitionEnd={event => {

            if (!covering && event.target === event.currentTarget && event.propertyName === "opacity") setFaded(true)
        }}

    >{pending[0]?.message ?? "Loading…"}</Loading>
}

function Desktop() {

    const application = ApplicationContext.useValue()
    const { preferences, resolved } = useDesktopPreferences()

    const [linkManager, setLinkManager] = useState<LinkManager | null>(null)

    const [connectionRevision, setConnectionRevision] = useState(0)

    const subscribe = useCallback(function () {

        return application.httpClient.onSubscribe<LinkManagerSnapshot>(function (link) {

            const manager = new LinkManager(application, link, link.payload, preferences, resolved)

            link.$internal.subscribeOnce("unsubscribe", () => {
                setLinkManager(current => current === manager ? null : current)
            })

            setLinkManager(manager)
        })
    }, [application, preferences, resolved])

    useEffect(subscribe, [subscribe])

    const connection = usePromise(async () => application.httpClient.subscribe(), [application, connectionRevision])

    if (connection.exception) return <FailedConnection

        exception={connection.exception.current}

        retry={() => setConnectionRevision(revision => revision + 1)}

    />

    if (!linkManager) return null

    return <ConnectedDesktop linkManager={linkManager} />
}

function FailedConnection({ exception, retry }: { exception: unknown, retry: () => void }) {

    useReady(connectionRequirement)

    useReady(sessionRequirement)

    useReady(wallpaperRequirement)

    return <Alert className="m-auto grid w-fit gap-3">

        <span>{String(exception)}</span>

        <button type="button" className="cursor-pointer justify-self-end" onClick={retry}>Try again</button>

    </Alert>
}

function ConnectedDesktop({ linkManager }: { linkManager: LinkManager }) {

    useReady(connectionRequirement)

    const { preferences, resolved, update } = useDesktopPreferences()

    const inbound = ReactTunnel.useFactory(linkManager.$inbound)

    inbound.useSubscribe("/change-desktop-preferences", useCallback(function (change: DesktopPreferencesUpdate) {
        update(change)
    }, [update]))

    const appearance = useProperty(linkManager.appearance)

    useRememberSystemAppearance(appearance)

    useEffect(function () {
        void linkManager.updateDesktopPreferences(preferences, resolved)
    }, [linkManager, preferences, resolved])

    return <LinkManagerContext.Provider value={linkManager}>

        <Authentication />

    </LinkManagerContext.Provider>
}