An open-source, self-hosted system for apps built with web technologies.
Unify desktop startup readiness
zohayrslileheb45e82c5fc5
diff --git a/package.json b/package.jsonindex d10ba8f..77aaf78 100644--- a/package.json+++ b/package.json@@ -30,7 +30,7 @@"build": "node --import tsx source/build.ts","start": "node --run build && node dist/server/main.js","pack": "node --run build && node --import tsx source/pack.ts",- "verify:contracts": "node --import tsx scripts/verify-client-launch.mjs",+ "verify:contracts": "node --import tsx scripts/verify-client-launch.mjs && node --import tsx scripts/verify-readiness.mjs","verify:distribution": "node scripts/verify-distribution.mjs","verify": "node --run check && node --run verify:contracts && node --run verify:distribution"},diff --git a/scripts/verify-readiness.mjs b/scripts/verify-readiness.mjsnew file mode 100644index 0000000..5b99a23--- /dev/null+++ b/scripts/verify-readiness.mjs@@ -0,0 +1,43 @@+import assert from "node:assert/strict"+import { createElement } from "react"+import { renderToStaticMarkup } from "react-dom/server"+import Readiness from "../source/libs/readiness/main.tsx"+import ReadinessState from "../source/libs/readiness/state.ts"++const startup = ReadinessState.start(["connection", "session", "wallpaper"])++assert.deepEqual(startup.pending, ["connection", "session", "wallpaper"])+assert.equal(startup.sealed, false)++const connected = startup.ready("connection")+const extended = connected.require("programs")+const session = extended.ready("session")+const wallpaper = session.ready("wallpaper")+const complete = wallpaper.ready("programs")++assert.deepEqual(connected.pending, ["session", "wallpaper"])+assert.deepEqual(extended.pending, ["session", "wallpaper", "programs"])+assert.deepEqual(complete.pending, [])+assert.equal(complete.sealed, true)+assert.equal(complete.ready("programs"), complete)++assert.throws(() => startup.ready("unknown"), /does not know/)+assert.throws(() => startup.require("session"), /already knows/)+assert.throws(() => complete.require("late"), /already complete/)+assert.throws(() => ReadinessState.start(["connection", "connection"]), /already knows/)+assert.throws(() => ReadinessState.start([""]), /must have a name/)++const pendingMarkup = renderToStaticMarkup(createElement(Readiness, { requirements: ["connection"] },+ createElement(Readiness.Pending, null, createElement("span", null, "Loading")),+ createElement("p", null, "Prepared content")+))++const readyMarkup = renderToStaticMarkup(createElement(Readiness, { requirements: [] },+ createElement(Readiness.Pending, null, createElement("span", null, "Loading")),+ createElement("p", null, "Prepared content")+))++assert.match(pendingMarkup, /Loading/)+assert.match(pendingMarkup, /Prepared content/)+assert.doesNotMatch(readyMarkup, /Loading/)+assert.match(readyMarkup, /Prepared content/)diff --git a/source/client/view/components/wallpaper.tsx b/source/client/view/components/wallpaper.tsxindex a18eb05..7c9f353 100644--- a/source/client/view/components/wallpaper.tsx+++ b/source/client/view/components/wallpaper.tsx@@ -108,13 +108,18 @@ function WallpaperLayer({ source, visible, onLoad }: { source: WallpaperSource,}/** A complete surface whose content sits above one file-backed wallpaper. */-export function WallpaperStage({ file, children }: { file: string | null, children: ReactNode }) {+export function WallpaperStage({ file, children, onReady }: WallpaperStageProps) {const [ready, setReady] = useState(false)return <div className="relative isolate grid min-h-0">- <WallpaperBackground file={file} onReady={() => setReady(true)} />+ <WallpaperBackground file={file} onReady={() => {++ setReady(true)++ onReady?.()+ }} /><div className="relative z-1 grid min-h-0">@@ -127,6 +132,15 @@ export function WallpaperStage({ file, children }: { file: string | null, childr</div>}+interface WallpaperStageProps {++ file: string | null++ children: ReactNode++ onReady?: () => void+}+interface WallpaperBackgroundProps {file: string | null | undefineddiff --git a/source/client/view/desktop/desktop.tsx b/source/client/view/desktop/desktop.tsxindex 44c8422..853b6b5 100644--- a/source/client/view/desktop/desktop.tsx+++ b/source/client/view/desktop/desktop.tsx@@ -9,13 +9,34 @@ import { ApplicationContext, LinkManagerContext } from "../contexts"import usePromise from "@libs/react-promise"import Session from "./session/session"import { useCallback, useState } from "react"+import Readiness, { useReadiness } from "@libs/readiness/main"+import { standardTheme } from "@phreshos/core"++const startupRequirements = ["connection", "session", "wallpaper"] as constexport default function () {+ return <Readiness requirements={startupRequirements}>++ <Desktop />++ <Readiness.Pending>++ <Loading style={{ backgroundColor: standardTheme.background, backdropFilter: "none" }} />++ </Readiness.Pending>++ </Readiness>+}++function Desktop() {+const application = ApplicationContext.useValue()const [linkManager, setLinkManager] = useState<LinkManager | null>(null)+ const { ready } = useReadiness()+const internal = ReactTunnel.useFactory(application.clientLink.$internal)internal.useSubscribe("subscribe", useCallback(function (socketLink: SocketLink<[TransmittedLinkManager, string]>) {@@ -25,11 +46,13 @@ export default function () {const [payload, connectionIdentity] = socketLink.payloadsetLinkManager(new LinkManager(application, socketLink, payload, connectionIdentity))- }, [application]))++ ready("connection")+ }, [application, ready]))usePromise(async () => application.clientLink.subscribe(), [])- if (!linkManager) return <Loading />+ if (!linkManager) return nullreturn <ConnectedDesktop linkManager={linkManager} />}diff --git a/source/client/view/desktop/session/session.tsx b/source/client/view/desktop/session/session.tsxindex e22e457..3f25052 100644--- a/source/client/view/desktop/session/session.tsx+++ b/source/client/view/desktop/session/session.tsx@@ -1,6 +1,5 @@import AuthManager from "@client/core/link-manager/auth-manager/auth-manager"import { AuthManagerContext, LinkManagerContext } from "../../contexts"-import Loading from "../../components/loading"import Alert from "../../components/alert"import usePromise from "@libs/react-promise"import useStorage from "@libs/storage-hook"@@ -8,10 +7,11 @@ import useCleanup from "@libs/cleanup-hook"import Workspace from "../workspace"import SignIn from "./sign-in"import Register from "./register"-import { useState } from "react"+import { useEffect, useState } from "react"import { type AuthenticationState } from "@server/core/authentication/authentication"import useProperty from "@libs/the-link/plugins/react-helper/property-hook"import { WallpaperStage } from "../../components/wallpaper"+import { useReadiness } from "@libs/readiness/main"export default function () {@@ -23,6 +23,8 @@ export default function () {const [revision, setRevision] = useState(0)+ const { ready } = useReadiness()+const sessionAuthenticate = usePromise<SessionResolution>(async function () {const response = await linkManager.sessionAuthenticate(authorization.value)@@ -43,7 +45,18 @@ export default function () {}, [sessionAuthenticate.solve])- if (sessionAuthenticate.isPending) return <Loading />+ const failed = sessionAuthenticate.exception !== undefined++ useEffect(function () {++ if (sessionAuthenticate.isPending) return++ ready("session")++ if (failed) ready("wallpaper")+ }, [failed, ready, sessionAuthenticate.isPending])++ if (sessionAuthenticate.isPending) return nullif (sessionAuthenticate.exception) return <Alert className="m-auto w-fit">@@ -51,13 +64,13 @@ export default function () {</Alert>- if (!sessionAuthenticate.solve) return <Loading />+ if (!sessionAuthenticate.solve) return nullif (sessionAuthenticate.solve.kind === "anonymous") return sessionAuthenticate.solve.authentication.registered- ? <WallpaperStage file={signInWallpaper}><SignIn /></WallpaperStage>+ ? <WallpaperStage file={signInWallpaper} onReady={() => ready("wallpaper")}><SignIn /></WallpaperStage>- : <WallpaperStage file={signInWallpaper}><Register state={sessionAuthenticate.solve.authentication} onClosed={() => setRevision(value => value + 1)} /></WallpaperStage>+ : <WallpaperStage file={signInWallpaper} onReady={() => ready("wallpaper")}><Register state={sessionAuthenticate.solve.authentication} onClosed={() => setRevision(value => value + 1)} /></WallpaperStage>return <AuthManagerContext.Provider value={sessionAuthenticate.solve.authManager}>diff --git a/source/client/view/desktop/workspace.tsx b/source/client/view/desktop/workspace.tsxindex 0dabc25..d31c0ba 100644--- a/source/client/view/desktop/workspace.tsx+++ b/source/client/view/desktop/workspace.tsx@@ -18,6 +18,7 @@ import useProperty from "@libs/the-link/plugins/react-helper/property-hook"import { WallpaperBackground } from "../components/wallpaper"import ProgramFrame from "./program-frame"import Loading from "../components/loading"+import { useReadiness } from "@libs/readiness/main"export default function Workspace() {@@ -25,6 +26,8 @@ export default function Workspace() {const authManager = AuthManagerContext.useValue()+ const { ready } = useReadiness()+const desktopWallpaper = useProperty(authManager.linkManager.desktopWallpaper)const windows = useWindows()@@ -58,11 +61,18 @@ export default function Workspace() {frameLoaded(wallpaper.identity, event.currentTarget)setReadyWallpaper(wallpaper.identity)++ ready("wallpaper")}- }, [frameLoaded, windows.wallpaper])+ }, [frameLoaded, ready, windows.wallpaper])++ const fileWallpaperLoaded = useCallback(() => {++ setFileWallpaperReady(true)- const fileWallpaperLoaded = useCallback(() => setFileWallpaperReady(true), [])+ ready("wallpaper")+ }, [ready])const focus = useDesktopFocus(desktop, windows)diff --git a/source/libs/readiness/main.tsx b/source/libs/readiness/main.tsxnew file mode 100644index 0000000..dee21eb--- /dev/null+++ b/source/libs/readiness/main.tsx@@ -0,0 +1,90 @@+import ReadinessState from "./state"+import { createContext, useCallback, useContext, useMemo, useRef, useState, type ReactNode } from "react"++const ReadinessContext = createContext<ReadinessValue | null>(null)++/** Provides one readiness lifecycle to every operation inside the boundary. */+export default function Readiness({ requirements, children }: ReadinessProps) {++ const declared = useRef<readonly string[] | null>(null)++ declared.current ??= [...requirements]++ if (!sameRequirements(declared.current, requirements)) throw new Error("Readiness requirements cannot change after the boundary mounts")++ const [state, setState] = useState(() => ReadinessState.start(requirements))++ const current = useRef(state)++ const change = useCallback(function (next: ReadinessState) {++ if (next === current.current) return++ current.current = next++ setState(next)+ }, [])++ const ready = useCallback(function (requirement: string) {++ change(current.current.ready(requirement))+ }, [change])++ const require = useCallback(function (requirement: string) {++ change(current.current.require(requirement))+ }, [change])++ const value = useMemo<ReadinessValue>(() => ({++ pending: state.pending,++ ready,++ require++ }), [ready, require, state.pending])++ return <ReadinessContext.Provider value={value}>{children}</ReadinessContext.Provider>+}++/** Renders one stable pending representation until every requirement is ready. */+function Pending({ children }: { children: ReactNode }) {++ const { pending } = useReadiness()++ return pending.length ? children : null+}++Readiness.Pending = Pending++/** Access the nearest readiness boundary. */+export function useReadiness() {++ const readiness = useContext(ReadinessContext)++ if (!readiness) throw new Error("Readiness was not provided")++ return readiness+}++function sameRequirements(left: readonly string[], right: readonly string[]) {++ return left.length === right.length && left.every((requirement, index) => requirement === right[index])+}++interface ReadinessProps {++ requirements: readonly string[]++ children: ReactNode+}++export interface ReadinessValue {++ pending: readonly string[]++ ready: (requirement: string) => void++ require: (requirement: string) => void+}diff --git a/source/libs/readiness/state.ts b/source/libs/readiness/state.tsnew file mode 100644index 0000000..980fcf3--- /dev/null+++ b/source/libs/readiness/state.ts@@ -0,0 +1,68 @@+/** The immutable state beneath a readiness boundary. */+export default class ReadinessState {++ public readonly requirements: readonly string[]++ public readonly pending: readonly string[]++ public readonly sealed: boolean++ private constructor(requirements: readonly string[], pending: readonly string[], sealed: boolean) {++ this.requirements = [...requirements]++ this.pending = [...pending]++ this.sealed = sealed+ }++ public static start(requirements: readonly string[]) {++ validate(requirements)++ return new ReadinessState(requirements, requirements, requirements.length === 0)+ }++ /** Mark one known requirement ready. Repeated readiness is harmless. */+ public ready(requirement: string) {++ if (!this.requirements.includes(requirement)) throw new Error(`Readiness does not know the requirement "${requirement}"`)++ if (!this.pending.includes(requirement)) return this++ const pending = this.pending.filter(candidate => candidate !== requirement)++ return new ReadinessState(this.requirements, pending, pending.length === 0)+ }++ /** Add work while the boundary is still pending. */+ public require(requirement: string) {++ validateRequirement(requirement)++ if (this.sealed) throw new Error("Readiness is already complete and cannot accept another requirement")++ if (this.requirements.includes(requirement)) throw new Error(`Readiness already knows the requirement "${requirement}"`)++ return new ReadinessState([...this.requirements, requirement], [...this.pending, requirement], false)+ }+}++function validate(requirements: readonly string[]) {++ const known = new Set<string>()++ for (const requirement of requirements) {++ validateRequirement(requirement)++ if (known.has(requirement)) throw new Error(`Readiness already knows the requirement "${requirement}"`)++ known.add(requirement)+ }+}++function validateRequirement(requirement: string) {++ if (!requirement.trim()) throw new Error("A readiness requirement must have a name")+}