An open-source, self-hosted system for apps built with web technologies.
Recompose desktop readiness across connections
zohayrslileha72ef99a1291
diff --git a/package.json b/package.jsonindex 7939c07..dec3518 100644--- a/package.json+++ b/package.json@@ -1,7 +1,7 @@{"name": "phreshos","displayName": "PhreshOS",- "version": "0.1.7",+ "version": "0.1.8","description": "The PhreshOS server, desktop, and authoritative system runtime.","type": "module","private": true,diff --git a/scripts/verify-readiness.mjs b/scripts/verify-readiness.mjsindex 5b99a23..f016ef6 100644--- a/scripts/verify-readiness.mjs+++ b/scripts/verify-readiness.mjs@@ -7,7 +7,6 @@ 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")@@ -18,12 +17,20 @@ 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)+const recomposed = complete.require("wallpaper").require("connection").require("session")++assert.deepEqual(recomposed.pending, ["connection", "session", "wallpaper"])+assert.deepEqual(recomposed.ready("connection").ready("session").ready("wallpaper").pending, [])+assert.equal(recomposed.require("connection"), recomposed)++const late = complete.require("late")++assert.deepEqual(late.requirements, ["connection", "session", "wallpaper", "programs", "late"])+assert.deepEqual(late.pending, ["late"])+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/)@@ -41,3 +48,14 @@ assert.match(pendingMarkup, /Loading/)assert.match(pendingMarkup, /Prepared content/)assert.doesNotMatch(readyMarkup, /Loading/)assert.match(readyMarkup, /Prepared content/)++const observedPendingMarkup = renderToStaticMarkup(createElement(Readiness, { requirements: ["connection", "session"] },+ createElement(Readiness.Pending, null, pending => createElement("span", null, pending.join(",")))+))++const observedReadyMarkup = renderToStaticMarkup(createElement(Readiness, { requirements: [] },+ createElement(Readiness.Pending, null, pending => createElement("span", null, String(pending.length)))+))++assert.match(observedPendingMarkup, /connection,session/)+assert.match(observedReadyMarkup, />0</)diff --git a/source/client/view/components/wallpaper.tsx b/source/client/view/components/wallpaper.tsxindex 7c9f353..701dcd3 100644--- a/source/client/view/components/wallpaper.tsx+++ b/source/client/view/components/wallpaper.tsx@@ -2,6 +2,7 @@ import bundledWallpaper from "@/assets/bundled/wallpaper.jpg"import { ApplicationContext } from "../contexts"import { useMemo, useState, type ReactNode } from "react"import Loading from "./loading"+import { useReady } from "@libs/readiness/main"type WallpaperSource = Readonly<{key: string@@ -108,17 +109,17 @@ function WallpaperLayer({ source, visible, onLoad }: { source: WallpaperSource,}/** A complete surface whose content sits above one file-backed wallpaper. */-export function WallpaperStage({ file, children, onReady }: WallpaperStageProps) {+export function WallpaperStage({ file, children }: WallpaperStageProps) {- const [ready, setReady] = useState(false)+ const [readyFile, setReadyFile] = useState<string | null>()++ const ready = readyFile === filereturn <div className="relative isolate grid min-h-0"><WallpaperBackground file={file} onReady={() => {- setReady(true)-- onReady?.()+ setReadyFile(file)}} /><div className="relative z-1 grid min-h-0">@@ -129,16 +130,23 @@ export function WallpaperStage({ file, children, onReady }: WallpaperStageProps){!ready && <Loading />}+ {ready && <ReadyWallpaper />}+</div>}+export function ReadyWallpaper() {++ useReady("wallpaper")++ return null+}+interface WallpaperStageProps {file: string | nullchildren: ReactNode-- onReady?: () => void}interface WallpaperBackgroundProps {diff --git a/source/client/view/desktop/desktop.tsx b/source/client/view/desktop/desktop.tsxindex 853b6b5..628aded 100644--- a/source/client/view/desktop/desktop.tsx+++ b/source/client/view/desktop/desktop.tsx@@ -9,7 +9,7 @@ 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 Readiness, { useReady } from "@libs/readiness/main"import { standardTheme } from "@phreshos/core"const startupRequirements = ["connection", "session", "wallpaper"] as const@@ -22,7 +22,15 @@ export default function () {<Readiness.Pending>- <Loading style={{ backgroundColor: standardTheme.background, backdropFilter: "none" }} />+ {pending => <Loading++ aria-hidden={pending.length === 0}++ className={`transition-opacity duration-200 ease-out ${pending.length ? "" : "pointer-events-none opacity-0"}`}++ style={{ backgroundColor: standardTheme.background, backdropFilter: "none" }}++ />}</Readiness.Pending>@@ -35,8 +43,6 @@ function Desktop() {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]>) {@@ -46,9 +52,7 @@ function Desktop() {const [payload, connectionIdentity] = socketLink.payloadsetLinkManager(new LinkManager(application, socketLink, payload, connectionIdentity))-- ready("connection")- }, [application, ready]))+ }, [application]))usePromise(async () => application.clientLink.subscribe(), [])@@ -59,6 +63,8 @@ function Desktop() {function ConnectedDesktop({ linkManager }: { linkManager: LinkManager }) {+ useReady("connection")+const theme = useProperty(linkManager.theme)return <LinkManagerContext.Provider value={linkManager}>diff --git a/source/client/view/desktop/session/session.tsx b/source/client/view/desktop/session/session.tsxindex 3f25052..8ac262e 100644--- a/source/client/view/desktop/session/session.tsx+++ b/source/client/view/desktop/session/session.tsx@@ -7,11 +7,11 @@ import useCleanup from "@libs/cleanup-hook"import Workspace from "../workspace"import SignIn from "./sign-in"import Register from "./register"-import { useEffect, useState } from "react"+import { useState, type ReactNode } 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"+import { useReady } from "@libs/readiness/main"export default function () {@@ -23,8 +23,6 @@ export default function () {const [revision, setRevision] = useState(0)- const { ready } = useReadiness()-const sessionAuthenticate = usePromise<SessionResolution>(async function () {const response = await linkManager.sessionAuthenticate(authorization.value)@@ -45,38 +43,59 @@ export default function () {}, [sessionAuthenticate.solve])- const failed = sessionAuthenticate.exception !== undefined+ if (sessionAuthenticate.isPending) return null- useEffect(function () {+ if (sessionAuthenticate.exception) return <FailedSession>- if (sessionAuthenticate.isPending) return+ <Alert className="m-auto w-fit">- ready("session")+ {String(sessionAuthenticate.exception.current)}- if (failed) ready("wallpaper")- }, [failed, ready, sessionAuthenticate.isPending])+ </Alert>- if (sessionAuthenticate.isPending) return null+ </FailedSession>- if (sessionAuthenticate.exception) return <Alert className="m-auto w-fit">+ if (!sessionAuthenticate.solve) return null- {String(sessionAuthenticate.exception.current)}+ if (sessionAuthenticate.solve.kind === "anonymous") return <ReadySession>- </Alert>+ {sessionAuthenticate.solve.authentication.registered- if (!sessionAuthenticate.solve) return null+ ? <WallpaperStage file={signInWallpaper}><SignIn /></WallpaperStage>++ : <WallpaperStage file={signInWallpaper}>++ <Register state={sessionAuthenticate.solve.authentication} onClosed={() => setRevision(value => value + 1)} />++ </WallpaperStage>}++ </ReadySession>- if (sessionAuthenticate.solve.kind === "anonymous") return sessionAuthenticate.solve.authentication.registered+ return <ReadySession>- ? <WallpaperStage file={signInWallpaper} onReady={() => ready("wallpaper")}><SignIn /></WallpaperStage>+ <AuthManagerContext.Provider value={sessionAuthenticate.solve.authManager}>++ <Workspace />++ </AuthManagerContext.Provider>++ </ReadySession>+}++function ReadySession({ children }: { children: ReactNode }) {++ useReady("session")++ return children+}- : <WallpaperStage file={signInWallpaper} onReady={() => ready("wallpaper")}><Register state={sessionAuthenticate.solve.authentication} onClosed={() => setRevision(value => value + 1)} /></WallpaperStage>+function FailedSession({ children }: { children: ReactNode }) {- return <AuthManagerContext.Provider value={sessionAuthenticate.solve.authManager}>+ useReady("session")- <Workspace />+ useReady("wallpaper")- </AuthManagerContext.Provider>+ return children}type SessionResolution = {diff --git a/source/client/view/desktop/workspace.tsx b/source/client/view/desktop/workspace.tsxindex d31c0ba..599c838 100644--- a/source/client/view/desktop/workspace.tsx+++ b/source/client/view/desktop/workspace.tsx@@ -15,10 +15,9 @@ import WindowTaskbarItem from "./taskbar/window-taskbar-item"import ProcessWindow from "./window-manager/process-window"import useWindows from "./window-manager/window-manager"import useProperty from "@libs/the-link/plugins/react-helper/property-hook"-import { WallpaperBackground } from "../components/wallpaper"+import { ReadyWallpaper, WallpaperBackground } from "../components/wallpaper"import ProgramFrame from "./program-frame"import Loading from "../components/loading"-import { useReadiness } from "@libs/readiness/main"export default function Workspace() {@@ -26,8 +25,6 @@ export default function Workspace() {const authManager = AuthManagerContext.useValue()- const { ready } = useReadiness()-const desktopWallpaper = useProperty(authManager.linkManager.desktopWallpaper)const windows = useWindows()@@ -61,18 +58,14 @@ export default function Workspace() {frameLoaded(wallpaper.identity, event.currentTarget)setReadyWallpaper(wallpaper.identity)-- ready("wallpaper")}- }, [frameLoaded, ready, windows.wallpaper])+ }, [frameLoaded, windows.wallpaper])const fileWallpaperLoaded = useCallback(() => {setFileWallpaperReady(true)-- ready("wallpaper")- }, [ready])+ }, [])const focus = useDesktopFocus(desktop, windows)@@ -253,5 +246,7 @@ export default function Workspace() {{!wallpaperReady && <Loading />}+ {wallpaperReady && <ReadyWallpaper />}+</div>}diff --git a/source/libs/readiness/main.tsx b/source/libs/readiness/main.tsxindex dee21eb..dbc930e 100644--- a/source/libs/readiness/main.tsx+++ b/source/libs/readiness/main.tsx@@ -1,5 +1,5 @@import ReadinessState from "./state"-import { createContext, useCallback, useContext, useMemo, useRef, useState, type ReactNode } from "react"+import { createContext, useCallback, useContext, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react"const ReadinessContext = createContext<ReadinessValue | null>(null)@@ -48,11 +48,13 @@ export default function Readiness({ requirements, children }: ReadinessProps) {return <ReadinessContext.Provider value={value}>{children}</ReadinessContext.Provider>}-/** Renders one stable pending representation until every requirement is ready. */-function Pending({ children }: { children: ReactNode }) {+/** Observe pending work or render one representation only while work remains. */+function Pending({ children }: PendingProps) {const { pending } = useReadiness()+ if (typeof children === "function") return children(pending)+return pending.length ? children : null}@@ -68,6 +70,34 @@ export function useReadiness() {return readiness}+/** Register pending work owned by this component and return its completion. */+export function useRequirement(requirement: string) {++ const { ready, require } = useReadiness()++ useLayoutEffect(function () {++ require(requirement)++ return () => ready(requirement)+ }, [ready, require, requirement])++ return useCallback(() => ready(requirement), [ready, requirement])+}++/** Treat this component's mounted presence as proof of readiness. */+export function useReady(requirement: string) {++ const { ready, require } = useReadiness()++ useLayoutEffect(function () {++ ready(requirement)++ return () => require(requirement)+ }, [ready, require, requirement])+}+function sameRequirements(left: readonly string[], right: readonly string[]) {return left.length === right.length && left.every((requirement, index) => requirement === right[index])@@ -80,6 +110,11 @@ interface ReadinessProps {children: ReactNode}+interface PendingProps {++ children: ReactNode | ((pending: readonly string[]) => ReactNode)+}+export interface ReadinessValue {pending: readonly string[]diff --git a/source/libs/readiness/state.ts b/source/libs/readiness/state.tsindex 980fcf3..173aa03 100644--- a/source/libs/readiness/state.ts+++ b/source/libs/readiness/state.ts@@ -5,22 +5,18 @@ export default class ReadinessState {public readonly pending: readonly string[]- public readonly sealed: boolean-- private constructor(requirements: readonly string[], pending: readonly string[], sealed: boolean) {+ private constructor(requirements: readonly string[], pending: readonly string[]) {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)+ return new ReadinessState(requirements, requirements)}/** Mark one known requirement ready. Repeated readiness is harmless. */@@ -32,19 +28,23 @@ export default class ReadinessState {const pending = this.pending.filter(candidate => candidate !== requirement)- return new ReadinessState(this.requirements, pending, pending.length === 0)+ return new ReadinessState(this.requirements, pending)}- /** Add work while the boundary is still pending. */+ /** Add new work or restore one completed requirement. */public require(requirement: string) {validateRequirement(requirement)- if (this.sealed) throw new Error("Readiness is already complete and cannot accept another requirement")+ if (this.pending.includes(requirement)) return this++ const requirements = this.requirements.includes(requirement)+ ? this.requirements+ : [...this.requirements, requirement]- if (this.requirements.includes(requirement)) throw new Error(`Readiness already knows the requirement "${requirement}"`)+ const restored = new Set([...this.pending, requirement])- return new ReadinessState([...this.requirements, requirement], [...this.pending, requirement], false)+ return new ReadinessState(requirements, requirements.filter(candidate => restored.has(candidate)))}}