An open-source, self-hosted system for apps built with web technologies.
Unify desktop animations with appearance transactions
zohayrslilehccdc504f46ba
diff --git a/bun.lock b/bun.lockindex 9dc2339..c9b3615 100644--- a/bun.lock+++ b/bun.lock@@ -15,9 +15,9 @@"@the-link/messagepack": "^0.1.0","@the-link/react": "^0.2.0","cfonts": "^3.3.1",- "gsap": "^3.15.0","hono": "^4.13.2","keyv": "^5.6.0",+ "motion": "^13.2.0","node-rsa": "^2.0.0","react": "^19.2.8","react-dom": "^19.2.8",@@ -381,8 +381,6 @@"graceful-fs": ["[email protected]", "", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="],- "gsap": ["[email protected]", "", {}, "sha512-dMW4CWBTUK1AEEDeZc1g4xpPGIrSf9fJF960qbTZmN/QwZIWY5wgliS6JWl9/25fpTGJrMRtSjGtOmPnfjZB+A=="],-"has-flag": ["[email protected]", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="],"hasown": ["[email protected]", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A=="],diff --git a/package.json b/package.jsonindex 728dce8..e04f790 100644--- a/package.json+++ b/package.json@@ -45,9 +45,9 @@"@the-link/messagepack": "^0.1.0","@the-link/react": "^0.2.0","cfonts": "^3.3.1",- "gsap": "^3.15.0","hono": "^4.13.2","keyv": "^5.6.0",+ "motion": "^13.2.0","node-rsa": "^2.0.0","react": "^19.2.8","react-dom": "^19.2.8",diff --git a/scripts/contracts/appearance.ts b/scripts/contracts/appearance.tsindex d7a13c8..40dcb80 100644--- a/scripts/contracts/appearance.ts+++ b/scripts/contracts/appearance.ts@@ -12,7 +12,7 @@ assert.deepEqual(appearanceSchema.parse(defaultAppearance), defaultAppearance)assert.throws(() => appearanceSchema.parse({}))assert.throws(() => appearanceSchema.parse({...defaultAppearance,- colors: { ...defaultAppearance.colors, accent: defaultAppearance.colors.primary }+ colors: { ...defaultAppearance.colors, accent: defaultAppearance.colors.light.primary }}))assert.throws(() => appearanceSchema.parse({ ...defaultAppearance, spacing: { light: 12, dark: 12 } }))assert.throws(() => appearanceSchema.parse({@@ -22,33 +22,46 @@ assert.throws(() => appearanceSchema.parse({dark: { ...defaultAppearance.material.dark, grain: 1.01 }}}))+assert.throws(() => appearanceSchema.parse({+ ...defaultAppearance,+ transaction: { duration: 120 }+}))const store = new Keyv()const directory = await mkdtemp(join(tmpdir(), "phresh-appearance-"))-const manager = await AppearanceManager.open(store, new UploadManager(new FileManager(directory)))+const uploads = new UploadManager(new FileManager(directory))+const manager = await AppearanceManager.open(store, uploads)assert.deepEqual(manager.value, defaultAppearance)assert(Object.isFrozen(manager.value))+assert.deepEqual(await store.get("appearance"), defaultAppearance)-for (const role of ["background", "foreground", "primary", "secondary", "success", "warning", "danger", "info"] as const) {+for (const theme of ["light", "dark"] as const) {+ for (const role of ["background", "foreground", "primary", "secondary", "success", "warning", "danger", "info"] as const) {+ const color = "oklch(60% 0.2 260)"+ const colors = {+ ...manager.value.colors,+ [theme]: { ...manager.value.colors[theme], [role]: color }+ }- assert.deepEqual((await store.get("appearance:colors"))[role], defaultAppearance.colors[role])- const color = { light: "oklch(60% 0.2 260)", dark: "var(--custom-color)" }- await manager.update({ ...manager.value, colors: { ...manager.value.colors, [role]: color } })- assert.deepEqual(manager.value.colors[role], color)- assert.deepEqual((await store.get("appearance:colors"))[role], color)- assert(Object.isFrozen(manager.value.colors[role]))+ await manager.update({ ...manager.value, colors })+ assert.equal(manager.value.colors[theme][role], color)+ assert.equal((await store.get("appearance")).colors[theme][role], color)+ assert(Object.isFrozen(manager.value.colors[theme]))- const current = manager.value- for (const invalid of [undefined, { light: "red" }, { light: "red", dark: "" }]) {+ const current = manager.value+ const invalidColors = {+ ...current.colors,+ [theme]: { ...current.colors[theme], [role]: "" }+ }- await assert.rejects(manager.update({ ...current, colors: { ...current.colors, [role]: invalid } }))+ await assert.rejects(manager.update({ ...current, colors: invalidColors }))assert.equal(manager.value, current)- assert.deepEqual((await store.get("appearance:colors"))[role], color)+ assert.deepEqual(await store.get("appearance"), current)}}-const reopened = await AppearanceManager.open(store, new UploadManager(new FileManager(directory)))+const reopened = await AppearanceManager.open(store, uploads)assert.deepEqual(reopened.value, manager.value)const shadow = {@@ -57,23 +70,24 @@ const shadow = {}await manager.update({ ...manager.value, shadow })assert.deepEqual(manager.value.shadow, shadow)-assert.deepEqual(await store.get("appearance:shadow"), shadow)-assert.deepEqual((await AppearanceManager.open(store, new UploadManager(new FileManager(directory)))).value.shadow, shadow)-for (const invalid of [{ ...shadow.light, blur: -1 }, { ...shadow.light, opacity: 1.1 }, { ...shadow.light, x: Infinity }]) {+assert.deepEqual((await store.get("appearance")).shadow, shadow)+assert.deepEqual((await AppearanceManager.open(store, uploads)).value.shadow, shadow)+for (const invalid of [{ ...shadow.light, blur: -1 }, { ...shadow.light, opacity: 1.1 }, { ...shadow.light, x: Infinity }]) {await assert.rejects(manager.update({ ...manager.value, shadow: { ...shadow, light: invalid } }))assert.deepEqual(manager.value.shadow, shadow)}const updated = {- ...defaultAppearance,- colors: { ...defaultAppearance.colors, background: { light: "white", dark: "black" } }+ ...manager.value,+ transaction: { duration: 180, easing: [0.25, 0.1, 0.25, 1] as const }}await manager.update(updated)-assert.deepEqual(manager.value.colors.background, updated.colors.background)-assert.deepEqual((await store.get("appearance:colors")).background, updated.colors.background)+assert.deepEqual(manager.value, updated)+assert.deepEqual(await store.get("appearance"), updated)+assert.equal(await store.get("appearance:colors"), undefined)assert.equal(await store.get("appearance:theme"), undefined)await rm(directory, { recursive: true, force: true })diff --git a/scripts/contracts/client-surface.ts b/scripts/contracts/client-surface.tsindex 07f59f6..775f379 100644--- a/scripts/contracts/client-surface.ts+++ b/scripts/contracts/client-surface.ts@@ -1,13 +1,15 @@import assert from "node:assert/strict"import ClientProcessBoundary from "@client/view/components/desktop-host/client-process-boundary"import ClientProcessManager from "@client/core/link-manager/auth-manager/process-manager/process-manager"-import { visualTransaction } from "@client/view/components/desktop-host/local-window"+import { parseLocalWindowTransaction } from "@client/view/components/desktop-host/local-window"import host from "@client/view/components/desktop-host/host"import LocalWindows from "@client/view/components/window-manager/local-windows"import type { LocalWindowEntry } from "@client/view/components/window-manager/local-windows"import ServerWindow from "@server/core/link-manager/auth-manager/process-manager/window"import type { LocalWindowState } from "@client/view/components/desktop-host/local-window"-import type { Transaction, WindowLayer } from "@phreshos/core"+import type { AppearanceTransaction, WaitedTransaction, WindowLayer } from "@phreshos/core"++type RequestedTransaction = AppearanceTransaction | WaitedTransactionconst authoritativeWindow = new ServerWindow({ title: "Target", layer: "over", location: "/" },@@ -20,13 +22,15 @@ const authoritativeWindow = new ServerWindow(assert.equal("surface" in authoritativeWindow, false)assert.equal("surface" in authoritativeWindow.toJSON(), false)-const transaction = visualTransaction({ duration: 240, easing: "ease-out", wait: true })-const visibility = visualTransaction({ duration: 240, easing: "ease-out", wait: true })!+const transaction = parseLocalWindowTransaction({ duration: 240, easing: "ease-out", wait: true })+const visibility = parseLocalWindowTransaction({ duration: 240, easing: "ease-out", wait: true })!-assert.throws(() => visualTransaction({}), /must provide duration or easing/)-assert.throws(() => visualTransaction({ wait: true }), /must provide duration or easing/)-assert.throws(() => visualTransaction({ duration: 60_001 }), /0 to 60000/)-assert.throws(() => visualTransaction({ unknown: true }), /no "unknown" field/)+assert.throws(() => parseLocalWindowTransaction({}), /must provide duration and easing/)+assert.throws(() => parseLocalWindowTransaction({ wait: true }), /must provide duration and easing/)+assert.throws(() => parseLocalWindowTransaction({ duration: 60_001, easing: "linear" }), /0 to 60000/)+assert.throws(() => parseLocalWindowTransaction({ duration: 120 }), /must provide duration and easing/)+assert.throws(() => parseLocalWindowTransaction({ duration: 120, easing: "linear", wait: false }), /must be true/)+assert.throws(() => parseLocalWindowTransaction({ unknown: true }), /no "unknown" field/)const ordinary = client("window")const bare = client("over")@@ -71,7 +75,7 @@ first.reconcile(clients)assert.deepEqual(first.state("ordinary").position, { x: 15, y: 25 })assert.deepEqual(first.state("bare").position, { x: 60, y: 70 })-const matchingAuthority = first.move("ordinary", { x: 30, y: 40 }, { duration: 120, wait: true })+const matchingAuthority = first.move("ordinary", { x: 30, y: 40 }, { duration: 120, easing: "ease-out", wait: true })const matchingRevision = represented(first, "ordinary:0").geometryAnimation!.revisionordinary.window.position = { x: 30, y: 40 }first.reconcile(clients)@@ -88,7 +92,7 @@ first.complete("bare", "geometry", geometryRevision)await waitingassert.equal(represented(first, "bare:0").geometryAnimation, null)-const interrupted = first.move("bare", { x: 100, y: 110 }, { duration: 200, wait: true })+const interrupted = first.move("bare", { x: 100, y: 110 }, { duration: 200, easing: "ease-out", wait: true })await first.move("bare", { x: 120, y: 130 })await assert.rejects(interrupted, /interrupted/)@@ -134,7 +138,7 @@ first.release("bare")assert.deepEqual(first.state("bare").position, bare.window.position)assert.equal(represented(first, "bare:0").surface, null)-const removed = first.move("bare", { x: 140, y: 150 }, { duration: 200, wait: true })+const removed = first.move("bare", { x: 140, y: 150 }, { duration: 200, easing: "ease-out", wait: true })const remaining = clients.get("ordinary")assert(remaining)first.reconcile(new Map([["ordinary", remaining]]))@@ -167,11 +171,11 @@ const processes = new Map<string, object>([[parent.identity, parent], [requesterconst calls: unknown[][] = []const localWindow = {state(identity: string) { return { position: identity === "target" ? { x: 70, y: 80 } : { x: 0, y: 0 } } },- move(identity: string, value: unknown, motion: Transaction | undefined) { calls.push(["move", identity, value, motion]) },- follow(identity: string, followed: string, motion: Transaction | undefined) { calls.push(["follow", identity, followed, motion]) },- unfollow(identity: string, motion: Transaction | undefined) { calls.push(["unfollow", identity, motion]) },- addSurface(identity: string, motion: Transaction) { calls.push(["add", identity, motion]) },- removeSurface(identity: string, motion: Transaction) { calls.push(["remove", identity, motion]) }+ move(identity: string, value: unknown, motion: RequestedTransaction | undefined) { calls.push(["move", identity, value, motion]) },+ follow(identity: string, followed: string, motion: RequestedTransaction | undefined) { calls.push(["follow", identity, followed, motion]) },+ unfollow(identity: string, motion: RequestedTransaction | undefined) { calls.push(["unfollow", identity, motion]) },+ addSurface(identity: string, motion: RequestedTransaction) { calls.push(["add", identity, motion]) },+ removeSurface(identity: string, motion: RequestedTransaction) { calls.push(["remove", identity, motion]) }}const processManager = {processes,diff --git a/source/client/view/appearance/appearance.tsx b/source/client/view/appearance/appearance.tsxindex a3f74fc..7959eac 100644--- a/source/client/view/appearance/appearance.tsx+++ b/source/client/view/appearance/appearance.tsx@@ -15,7 +15,7 @@ export default function ({ children }: PropsWithChildren) {function AppearanceRoot({ children }: PropsWithChildren) {const { preferences } = useDesktopPreferences()- const background = defaultAppearance.colors.background[preferences.theme]+ const background = defaultAppearance.colors[preferences.theme].backgroundreturn <ReducedMotion reduced={!preferences.animations}>diff --git a/source/client/view/appearance/motion.ts b/source/client/view/appearance/motion.tsindex c0df95c..d91e2e7 100644--- a/source/client/view/appearance/motion.ts+++ b/source/client/view/appearance/motion.ts@@ -1,52 +1,31 @@-import { type Easing } from "@phreshos/core"-import gsap from "gsap"-import { CustomEase } from "gsap/CustomEase"+import { type AppearanceTransaction, type Easing } from "@phreshos/core"+import { type Transition } from "motion/react"-gsap.registerPlugin(CustomEase)--const curves: Record<Exclude<Easing, readonly number[]>, readonly [number, number, number, number]> = {- linear: [0, 0, 1, 1],+const easings: Record<Exclude<Easing, readonly number[]>, Transition["ease"]> = {+ linear: "linear",ease: [0.25, 0.1, 0.25, 1],- "ease-in": [0.42, 0, 1, 1],- "ease-out": [0, 0, 0.58, 1],- "ease-in-out": [0.42, 0, 0.58, 1]+ "ease-in": "easeIn",+ "ease-out": "easeOut",+ "ease-in-out": "easeInOut"}-const registered = new Map<string, gsap.EaseFunction>()--/** Shared interaction timings in the same millisecond unit as public transactions. */-export const motionDurations = Object.freeze({- control: 100,- minimize: 110,- close: 160,- snap: 180,- feedback: 200,- morph: 220,- presence: 240,- restore: 240,- geometry: 300-})--/** Preserves public CSS timing curves while GSAP owns their interpolation. */-export function motionEase(value: Easing | undefined, fallback: Easing = "ease-out") {-- const selected = value ?? fallback- const points = typeof selected === "string" ? curves[selected] : selected- const key = points.join(",")- const existing = registered.get(key)+/** Translates the public Appearance timing contract into Motion's units. */+export function motionTransition(transaction: AppearanceTransaction, reduced = false): Transition {- if (existing) return existing-- const easing = CustomEase.create(`phresh-${registered.size}`, key)+ return {+ type: "tween",+ duration: reduced ? 0 : transaction.duration / 1_000,+ ease: motionEase(transaction.easing)+ }+}- registered.set(key, easing)+/** Translates the public easing vocabulary into a CSS timing function. */+export function cssEasing(easing: Easing) {- return easing+ return typeof easing === "string" ? easing : "cubic-bezier(" + easing.join(", ") + ")"}-export default gsap--export function motionDuration(milliseconds: number) {+function motionEase(easing: Easing): Transition["ease"] {- return milliseconds / 1_000+ return typeof easing === "string" ? easings[easing] : [...easing]}diff --git a/source/client/view/appearance/surface-presence.ts b/source/client/view/appearance/surface-presence.tsindex 0008a75..a7feda8 100644--- a/source/client/view/appearance/surface-presence.ts+++ b/source/client/view/appearance/surface-presence.ts@@ -1,89 +1,14 @@-import { type Easing } from "@phreshos/core"-import gsap, { motionDuration, motionDurations, motionEase } from "./motion"+import { type AppearanceTransaction } from "@phreshos/core"+import { type DOMKeyframesDefinition, type Transition } from "motion/react"+import { motionTransition } from "./motion"-const entered = { scale: 1, y: 0 }+export const surfacePresencePose = Object.freeze({+ entered: { scale: 1, y: 0, opacity: 1 },+ entering: { scale: 0.96, y: 8, opacity: 0 }+}) satisfies Record<string, DOMKeyframesDefinition>-const entering = { scale: 0.96, y: 8 }+/** One shared presence transition owned by Appearance. */+export function surfacePresenceTransition(reducedMotion: boolean, transaction: AppearanceTransaction): Transition {-interface SurfacePresenceTransition {-- duration?: number-- easing?: Easing-- onComplete?: () => void-}--/** Establish the first frame before a surface becomes visible. */-export function prepareSurfaceEntrance(surface: HTMLElement | null, reducedMotion: boolean) {-- if (!surface) return-- gsap.killTweensOf(surface)-- gsap.set(surface, reducedMotion ? entered : entering)-}--/** Give every system surface the same entrance motion. */-export function enterSurface(surface: HTMLElement | null, reducedMotion: boolean, transition: SurfacePresenceTransition = {}) {-- if (!surface) return null-- gsap.killTweensOf(surface)-- const duration = transition.duration ?? motionDurations.presence-- if (reducedMotion || duration === 0) {-- gsap.set(surface, entered)-- transition.onComplete?.()-- return null- }-- return gsap.to(surface, {- ...entered,- duration: motionDuration(duration),- ease: transition.easing === undefined ? "power3.out" : motionEase(transition.easing),- overwrite: "auto",- onComplete: transition.onComplete- })-}--/** Reverse the shared entrance pose when a Surface leaves. */-export function leaveSurface(surface: HTMLElement | null, reducedMotion: boolean, transition: SurfacePresenceTransition = {}) {-- if (!surface) return null-- gsap.killTweensOf(surface)-- const duration = transition.duration ?? motionDurations.presence-- if (reducedMotion || duration === 0) {-- gsap.set(surface, entered)-- transition.onComplete?.()-- return null- }-- return gsap.to(surface, {- ...entering,- duration: motionDuration(duration),- ease: transition.easing === undefined ? "power3.in" : motionEase(transition.easing),- overwrite: "auto",- onComplete: transition.onComplete- })-}--/** Stop presence motion and leave the surface ready for its next entrance. */-export function restSurface(surface: HTMLElement | null) {-- if (!surface) return-- gsap.killTweensOf(surface)-- gsap.set(surface, entered)+ return motionTransition(transaction, reducedMotion)}diff --git a/source/client/view/components/desktop-host/host.ts b/source/client/view/components/desktop-host/host.tsindex 1890fc2..e6f12d9 100644--- a/source/client/view/components/desktop-host/host.ts+++ b/source/client/view/components/desktop-host/host.ts@@ -23,7 +23,7 @@ import {localPosition,localSize,requireLocalWindowLayer,- visualTransaction,+ parseLocalWindowTransaction,type LocalWindowHost} from "./local-window"import SystemAccess from "./system-access"@@ -728,7 +728,7 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()const target = localProcess(args[0])requireLocalWindowLayer(target.client!.window.layer)- await localWindow.move(target.identity, localPosition(args[1]), visualTransaction(args[2]))+ await localWindow.move(target.identity, localPosition(args[1]), parseLocalWindowTransaction(args[2]))return []}@@ -737,7 +737,7 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()const target = localProcess(args[0])requireLocalWindowLayer(target.client!.window.layer)- await localWindow.resize(target.identity, localSize(args[1]), visualTransaction(args[2]))+ await localWindow.resize(target.identity, localSize(args[1]), parseLocalWindowTransaction(args[2]))return []}@@ -746,7 +746,7 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()const target = localProcess(args[0])requireLocalWindowLayer(target.client!.window.layer)- await localWindow.geometry(target.identity, localGeometry(args[1]), visualTransaction(args[2]))+ await localWindow.geometry(target.identity, localGeometry(args[1]), parseLocalWindowTransaction(args[2]))return []}@@ -755,7 +755,7 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()const target = localProcess(args[0])requireLocalWindowLayer(target.client!.window.layer)- await localWindow.addSurface(target.identity, visualTransaction(args[2]))+ await localWindow.addSurface(target.identity, parseLocalWindowTransaction(args[2]))return []}@@ -764,7 +764,7 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()const target = localProcess(args[0])requireLocalWindowLayer(target.client!.window.layer)- await localWindow.removeSurface(target.identity, visualTransaction(args[2]))+ await localWindow.removeSurface(target.identity, parseLocalWindowTransaction(args[2]))return []}@@ -776,7 +776,7 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()if (typeof args[1] !== "boolean") throw new Error("Local Window minimize takes a boolean state")- await localWindow.minimize(target.identity, args[1], visualTransaction(args[2]))+ await localWindow.minimize(target.identity, args[1], parseLocalWindowTransaction(args[2]))return []}@@ -787,7 +787,7 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()requireLocalWindowLayer(target.client!.window.layer)const followed = await permittedProcess(args[1])clientOf(followed)- await localWindow.follow(target.identity, followed.identity, visualTransaction(args[2]))+ await localWindow.follow(target.identity, followed.identity, parseLocalWindowTransaction(args[2]))return []}@@ -796,7 +796,7 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()const target = localProcess(args[0])requireLocalWindowLayer(target.client!.window.layer)- await localWindow.unfollow(target.identity, visualTransaction(args[1]))+ await localWindow.unfollow(target.identity, parseLocalWindowTransaction(args[1]))return []}diff --git a/source/client/view/components/desktop-host/local-window.ts b/source/client/view/components/desktop-host/local-window.tsindex fb64a67..3b9cb60 100644--- a/source/client/view/components/desktop-host/local-window.ts+++ b/source/client/view/components/desktop-host/local-window.ts@@ -1,9 +1,11 @@import {+ appearanceLimits,isRelativeValue,+ type AppearanceTransaction,type Easing,type Position,type Size,- type Transaction,+ type WaitedTransaction,type WindowGeometry,type WindowLayer,type WindowState@@ -11,7 +13,7 @@ import {export type LocalAnimation = Readonly<{revision: number- transaction: Transaction+ transaction: AppearanceTransaction}>export type LocalSurfaceState = Readonly<{@@ -30,16 +32,16 @@ export type LocalWindowState = WindowState & Readonly<{/** The only interface through which an iframe changes its local representation. */export interface LocalWindowHost {state(identity: string): WindowState- move(identity: string, position: Position, transaction?: Transaction): Promise<void>- resize(identity: string, size: Size, transaction?: Transaction): Promise<void>- geometry(identity: string, geometry: WindowGeometry, transaction?: Transaction): Promise<void>- minimize(identity: string, minimized: boolean, transaction?: Transaction): Promise<void>- follow(identity: string, target: string, transaction?: Transaction): Promise<void>- unfollow(identity: string, transaction?: Transaction): Promise<void>+ move(identity: string, position: Position, transaction?: AppearanceTransaction | WaitedTransaction): Promise<void>+ resize(identity: string, size: Size, transaction?: AppearanceTransaction | WaitedTransaction): Promise<void>+ geometry(identity: string, geometry: WindowGeometry, transaction?: AppearanceTransaction | WaitedTransaction): Promise<void>+ minimize(identity: string, minimized: boolean, transaction?: AppearanceTransaction | WaitedTransaction): Promise<void>+ follow(identity: string, target: string, transaction?: AppearanceTransaction | WaitedTransaction): Promise<void>+ unfollow(identity: string, transaction?: AppearanceTransaction | WaitedTransaction): Promise<void>title(identity: string, title: string): voidraise(identity: string): void- addSurface(identity: string, transaction?: Transaction): Promise<void>- removeSurface(identity: string, transaction?: Transaction): Promise<void>+ addSurface(identity: string, transaction?: AppearanceTransaction | WaitedTransaction): Promise<void>+ removeSurface(identity: string, transaction?: AppearanceTransaction | WaitedTransaction): Promise<void>complete(identity: string, kind: "geometry" | "minimize" | "surface", revision: number): voidrelease(identity: string): void}@@ -66,31 +68,28 @@ export function localGeometry(value: unknown): WindowGeometry {return Object.freeze({ position: localPosition(record.position), size: localSize(record.size) })}-export function visualTransaction(value: unknown): Transaction | undefined {+export function parseLocalWindowTransaction(value: unknown): AppearanceTransaction | WaitedTransaction | undefined {if (value === undefined) return undefined- const record = plain(value, "Transaction")- fields(record, ["duration", "easing", "wait"], "Transaction")+ const record = plain(value, "Appearance transaction")+ fields(record, ["duration", "easing", "wait"], "Appearance transaction")- if (!("duration" in record) && !("easing" in record)) throw new Error("A Transaction must provide duration or easing")+ if (!("duration" in record) || !("easing" in record)) throw new Error("An Appearance transaction must provide duration and easing")+ const { minimum, maximum } = appearanceLimits.transaction.duration+ if (!finite(record.duration) || record.duration < minimum || record.duration > maximum) throw new Error(`Appearance transaction duration must be finite milliseconds from ${minimum} to ${maximum}`)- const result: { duration?: number, easing?: Easing, wait?: boolean } = {}-- if ("duration" in record) {-- if (!finite(record.duration) || record.duration < 0 || record.duration > 60_000) throw new Error("Transaction duration must be finite milliseconds from 0 to 60000")- result.duration = record.duration+ const result: { duration: number, easing: Easing, wait?: true } = {+ duration: record.duration,+ easing: easing(record.easing)}- if ("easing" in record) result.easing = easing(record.easing)-if ("wait" in record) {- if (typeof record.wait !== "boolean") throw new Error("Transaction wait must be a boolean")- result.wait = record.wait+ if (record.wait !== true) throw new Error("Appearance transaction wait must be true when present")+ result.wait = true}- return Object.freeze(result) as Transaction+ return Object.freeze(result)}export function requireLocalWindowLayer(layer: WindowLayer) {@@ -100,7 +99,7 @@ export function requireLocalWindowLayer(layer: WindowLayer) {function easing(value: unknown): Easing {if (value === "linear" || value === "ease" || value === "ease-in" || value === "ease-out" || value === "ease-in-out") return value- if (!Array.isArray(value) || value.length !== 4 || !value.every(finite) || value[0] < 0 || value[0] > 1 || value[2] < 0 || value[2] > 1) throw new Error("Transaction easing must be a standard easing name or four cubic Bézier numbers with x values from 0 to 1")+ if (!Array.isArray(value) || value.length !== 4 || !value.every(finite) || value[0] < 0 || value[0] > 1 || value[2] < 0 || value[2] > 1) throw new Error("Appearance transaction easing must be a standard easing name or four cubic Bézier numbers with x values from 0 to 1")return Object.freeze([...value]) as [number, number, number, number]}diff --git a/source/client/view/components/window-manager/local-windows.ts b/source/client/view/components/window-manager/local-windows.tsindex 4ab4b7a..4e40e70 100644--- a/source/client/view/components/window-manager/local-windows.ts+++ b/source/client/view/components/window-manager/local-windows.ts@@ -1,5 +1,10 @@import ClientState from "@client/core/link-manager/auth-manager/process-manager/client-state"-import { type Transaction, type WindowGeometry, type WindowState } from "@phreshos/core"+import {+ type AppearanceTransaction,+ type WaitedTransaction,+ type WindowGeometry,+ type WindowState+} from "@phreshos/core"import { type LocalWindowHost, type LocalWindowState } from "../desktop-host/local-window"export interface LocalWindowEntry {@@ -115,35 +120,35 @@ export default class LocalWindows implements LocalWindowHost {else this.readers.delete(identity)}- public move(process: string, position: WindowState["position"], transaction?: Transaction) {+ public move(process: string, position: WindowState["position"], transaction?: RequestedTransaction) {const { identity, state } = this.existing(process)this.following.delete(identity)return this.changeGeometry(identity, { position, size: state.size }, transaction)}- public resize(process: string, size: WindowState["size"], transaction?: Transaction) {+ public resize(process: string, size: WindowState["size"], transaction?: RequestedTransaction) {const { identity, state } = this.existing(process)this.following.delete(identity)return this.changeGeometry(identity, { position: state.position, size }, transaction)}- public geometry(process: string, value: WindowGeometry, transaction?: Transaction) {+ public geometry(process: string, value: WindowGeometry, transaction?: RequestedTransaction) {const { identity } = this.existing(process)this.following.delete(identity)return this.changeGeometry(identity, value, transaction)}- public minimize(process: string, minimized: boolean, transaction?: Transaction) {+ public minimize(process: string, minimized: boolean, transaction?: RequestedTransaction) {const { identity } = this.existing(process)this.following.delete(identity)return this.changeMinimized(identity, minimized, transaction)}- public follow(process: string, targetProcess: string, transaction?: Transaction) {+ public follow(process: string, targetProcess: string, transaction?: RequestedTransaction) {const follower = this.existing(process)const target = this.existing(targetProcess)@@ -184,7 +189,7 @@ export default class LocalWindows implements LocalWindowHost {]).then(() => undefined)}- public unfollow(process: string, transaction?: Transaction) {+ public unfollow(process: string, transaction?: RequestedTransaction) {const { identity } = this.existing(process)const relation = this.following.get(identity)@@ -216,26 +221,26 @@ export default class LocalWindows implements LocalWindowHost {this.replace(identity, { ...state, depth: depth + 1 })}- public addSurface(process: string, transaction?: Transaction) {+ public addSurface(process: string, transaction?: RequestedTransaction) {const { identity, state } = this.existing(process)if (state.surface?.visible) return Promise.resolve()this.cancel(identity, "surface")- const transition = transaction ? { revision: ++this.revision, transaction } : null+ const transition = transaction ? localAnimation(++this.revision, transaction) : nullthis.replace(identity, { ...state, surface: { visible: true, transition } })- return this.waitFor(identity, "surface", transition)+ return this.waitFor(identity, "surface", transition, transaction)}- public removeSurface(process: string, transaction?: Transaction) {+ public removeSurface(process: string, transaction?: RequestedTransaction) {const { identity, state } = this.existing(process)if (!state.surface || !state.surface.visible) return Promise.resolve()this.cancel(identity, "surface")- const transition = transaction ? { revision: ++this.revision, transaction } : null+ const transition = transaction ? localAnimation(++this.revision, transaction) : nullthis.replace(identity, { ...state, surface: { visible: false, transition } })- return this.waitFor(identity, "surface", transition)+ return this.waitFor(identity, "surface", transition, transaction)}public complete(process: string, kind: AnimationKind, revision: number) {@@ -296,33 +301,33 @@ export default class LocalWindows implements LocalWindowHost {this.publish(next)}- private changeGeometry(identity: string, value: WindowGeometry, transaction?: Transaction, project = true) {+ private changeGeometry(identity: string, value: WindowGeometry, transaction?: RequestedTransaction, project = true) {const state = this.windows.get(identity)if (!state) throw new Error("This Client has no local Window representation")if (JSON.stringify([state.position, state.size]) === JSON.stringify([value.position, value.size])) return Promise.resolve()this.cancel(identity, "geometry")- const animation = transaction ? { revision: ++this.revision, transaction } : null+ const animation = transaction ? localAnimation(++this.revision, transaction) : nullthis.replace(identity, { ...state, position: value.position, size: value.size, geometryAnimation: animation })if (project) this.projectFollowers(identity, transaction)- return this.waitFor(identity, "geometry", animation)+ return this.waitFor(identity, "geometry", animation, transaction)}- private changeMinimized(identity: string, minimized: boolean, transaction?: Transaction, project = true) {+ private changeMinimized(identity: string, minimized: boolean, transaction?: RequestedTransaction, project = true) {const state = this.windows.get(identity)if (!state) throw new Error("This Client has no local Window representation")if (state.minimized === minimized) return Promise.resolve()this.cancel(identity, "minimize")- const animation = transaction ? { revision: ++this.revision, transaction } : null+ const animation = transaction ? localAnimation(++this.revision, transaction) : nullthis.replace(identity, { ...state, minimized, minimizeAnimation: animation })if (project) this.projectFollowers(identity, transaction)- return this.waitFor(identity, "minimize", animation)+ return this.waitFor(identity, "minimize", animation, transaction)}- private projectFollowers(target: string, transaction?: Transaction, visited = new Set<string>()) {+ private projectFollowers(target: string, transaction?: RequestedTransaction, visited = new Set<string>()) {if (visited.has(target)) returnvisited.add(target)@@ -330,7 +335,7 @@ export default class LocalWindows implements LocalWindowHost {const targetState = this.windows.get(target)if (!targetState) return- const selected = transaction ? { ...transaction, wait: false } : undefined+ const selected = transaction ? baseTransaction(transaction) : undefinedfor (const [identity, relation] of this.following) {@@ -364,9 +369,9 @@ export default class LocalWindows implements LocalWindowHost {waiting.reject(new Error(reason))}- private waitFor(identity: string, kind: AnimationKind, animation: LocalWindowState["geometryAnimation"]) {+ private waitFor(identity: string, kind: AnimationKind, animation: LocalWindowState["geometryAnimation"], transaction?: RequestedTransaction) {- if (!animation?.transaction.wait) return Promise.resolve()+ if (!animation || !transaction || !("wait" in transaction)) return Promise.resolve()return new Promise<void>((resolve, reject) => {this.waiting.set(animationKey(identity, kind), { revision: animation.revision, resolve, reject })@@ -375,6 +380,7 @@ export default class LocalWindows implements LocalWindowHost {}type AnimationKind = "geometry" | "minimize" | "surface"+type RequestedTransaction = AppearanceTransaction | WaitedTransactioninterface WaitingAnimation {revision: number@@ -396,6 +402,16 @@ function animationKey(identity: string, kind: AnimationKind) {return `${identity}:${kind}`}+function baseTransaction(transaction: RequestedTransaction): AppearanceTransaction {++ return Object.freeze({ duration: transaction.duration, easing: transaction.easing })+}++function localAnimation(revision: number, transaction: RequestedTransaction) {++ return Object.freeze({ revision, transaction: baseTransaction(transaction) })+}+function localState(client: ClientState): LocalWindowState {const window = client.windowdiff --git a/source/client/view/structure/authentication/authentication.tsx b/source/client/view/structure/authentication/authentication.tsxindex 71f4cb8..ca6559c 100644--- a/source/client/view/structure/authentication/authentication.tsx+++ b/source/client/view/structure/authentication/authentication.tsx@@ -11,7 +11,7 @@ import { useState, type ReactNode } from "react"import { type AuthenticationState } from "@server/core/authentication/authentication"import { WallpaperStage } from "../desktop/wallpaper/wallpaper"import { useReady } from "@libs/readiness"-import { useAppearance, useResolveTheme } from "@phreshos/react-ui"+import { useAppearance, useThemedValue } from "@phreshos/react-ui"export default function () {@@ -19,7 +19,7 @@ export default function () {const linkManager = LinkManagerContext.useValue()- const signInWallpaper = useResolveTheme(useAppearance().signInWallpaper)+ const signInWallpaper = useThemedValue(useAppearance().signInWallpaper)const [revision, setRevision] = useState(0)diff --git a/source/client/view/structure/authentication/credentials-form.tsx b/source/client/view/structure/authentication/credentials-form.tsxindex 8cc77ac..4b076eb 100644--- a/source/client/view/structure/authentication/credentials-form.tsx+++ b/source/client/view/structure/authentication/credentials-form.tsx@@ -1,32 +1,17 @@import { type AuthenticationState } from "@server/core/authentication/authentication"-import { enterSurface, prepareSurfaceEntrance, restSurface } from "../../appearance/surface-presence"+import { surfacePresencePose, surfacePresenceTransition } from "../../appearance/surface-presence"import { useReducedMotion } from "@libs/react-motion"-import { Panel } from "@phreshos/react-ui"+import { motion } from "motion/react"+import { Panel, useAppearance } from "@phreshos/react-ui"import Spinner from "../../components/spinner"import Alert from "../../components/alert"-import { type SyntheticEvent, useLayoutEffect, useRef } from "react"+import { type SyntheticEvent } from "react"/** The common username-and-password surface for registration and sign-in. */export default function CredentialsForm({ title, description, submitLabel, passwordAutocomplete, requirements, error, pending, onSubmit }: CredentialsFormProps) {- const surface = useRef<HTMLFormElement>(null)-const reducedMotion = useReducedMotion()-- useLayoutEffect(function () {-- prepareSurfaceEntrance(surface.current, reducedMotion)-- const entrance = enterSurface(surface.current, reducedMotion)-- return () => {-- entrance?.kill()-- restSurface(surface.current)- }-- }, [reducedMotion])+ const transaction = useAppearance().transactionfunction submit(event: SyntheticEvent<HTMLFormElement, SubmitEvent>) {@@ -41,9 +26,13 @@ export default function CredentialsForm({ title, description, submitLabel, passwreturn <div className="absolute inset-0 grid backdrop-blur-md">- <form+ <motion.form++ initial={reducedMotion ? surfacePresencePose.entered : surfacePresencePose.entering}++ animate={surfacePresencePose.entered}- ref={surface}+ transition={surfacePresenceTransition(reducedMotion, transaction)}className="relative m-auto w-[min(24rem,calc(100%-2rem))]"@@ -143,7 +132,7 @@ export default function CredentialsForm({ title, description, submitLabel, passw</Panel>- </form>+ </motion.form></div>}diff --git a/source/client/view/structure/desktop/desktop.tsx b/source/client/view/structure/desktop/desktop.tsxindex 1cc8d87..077424f 100644--- a/source/client/view/structure/desktop/desktop.tsx+++ b/source/client/view/structure/desktop/desktop.tsx@@ -17,7 +17,7 @@ import useWindows from "../../components/window-manager/window-manager"import { ReadyWallpaper, WallpaperBackground } from "./wallpaper/wallpaper"import Loading from "../../components/loading"import { useRequirement } from "@libs/readiness"-import { useAppearance, useResolveTheme, useTheme } from "@phreshos/react-ui"+import { useAppearance, useThemedValue, useTheme } from "@phreshos/react-ui"export default function Workspace() {@@ -27,9 +27,9 @@ export default function Workspace() {const appearance = useAppearance()- const desktopWallpaper = useResolveTheme(appearance.desktopWallpaper)+ const desktopWallpaper = useThemedValue(appearance.desktopWallpaper)- const foreground = useResolveTheme(appearance.colors.foreground)+ const foreground = useThemedValue(appearance.colors).foregroundconst theme = useTheme()diff --git a/source/client/view/structure/desktop/taskbar/launcher/launcher.tsx b/source/client/view/structure/desktop/taskbar/launcher/launcher.tsxindex 485223c..2561ebf 100644--- a/source/client/view/structure/desktop/taskbar/launcher/launcher.tsx+++ b/source/client/view/structure/desktop/taskbar/launcher/launcher.tsx@@ -1,23 +1,29 @@import { type ComponentPropsWithoutRef, ReactNode, useCallback, useEffect, useId, useRef, useState } from "react"-import { enterSurface, prepareSurfaceEntrance, restSurface } from "@client/view/appearance/surface-presence"+import { surfacePresenceTransition } from "@client/view/appearance/surface-presence"+import { cssEasing } from "@client/view/appearance/motion"import { useReducedMotion } from "@libs/react-motion"+import { motion } from "motion/react"import { taskbarSurfaceClassName } from "../taskbar-surface"import TaskbarButton from "../taskbar-button"+import { useAppearance } from "@phreshos/react-ui"/*** A button and the dismissible surface it opens. Placement, contents and* what selecting an item means belong to the caller.*/-export default function ({ label, trigger, children, className, ...props }: LauncherProps) {+export default function ({ label, trigger, children, className, style, ...props }: LauncherProps) {const id = useId()const surface = useRef<HTMLDivElement>(null)const reducedMotion = useReducedMotion()+ const transaction = useAppearance().transactionconst [open, setOpen] = useState(false)+ const openAtPressStart = useRef(false)+const close = useCallback(function () {const element = surface.current@@ -26,15 +32,26 @@ export default function ({ label, trigger, children, className, ...props }: Laun}, [])+ const beginToggle = useCallback(function () {++ openAtPressStart.current = surface.current?.matches(":popover-open") ?? false++ }, [])+const toggle = useCallback(function () {const element = surface.currentif (!element) return- if (element.matches(":popover-open")) element.hidePopover()+ if (openAtPressStart.current) {- else element.showPopover()+ if (element.matches(":popover-open")) element.hidePopover()++ return+ }++ if (!element.matches(":popover-open")) element.showPopover()}, [])@@ -69,6 +86,8 @@ export default function ({ label, trigger, children, className, ...props }: Launaria-label={label}+ onPressStart={beginToggle}+onPress={toggle}>@@ -77,7 +96,7 @@ export default function ({ label, trigger, children, className, ...props }: Laun</TaskbarButton>- <div+ <motion.div{...props}@@ -93,42 +112,50 @@ export default function ({ label, trigger, children, className, ...props }: LauntabIndex={-1}+ style={{+ ...style,+ transitionBehavior: "allow-discrete",+ transitionDuration: reducedMotion ? "0ms" : String(transaction.duration) + "ms",+ transitionTimingFunction: cssEasing(transaction.easing),+ transitionProperty: "display, overlay"+ }}+className={`${taskbarSurfaceClassName} hidden open:block ${className ?? ""}`}+ initial={false}++ animate={open ? { scale: 1, opacity: 1 } : { scale: 1.05, opacity: 0 }}++ transition={surfacePresenceTransition(reducedMotion, transaction)}+onBeforeToggle={event => {- if (event.newState === "open") prepareSurfaceEntrance(event.currentTarget, reducedMotion)+ setOpen(event.newState === "open")}}onToggle={event => {const opening = event.newState === "open"- setOpen(opening)-if (opening) {- enterSurface(event.currentTarget, reducedMotion)-const focusTarget = event.currentTarget.querySelector<HTMLElement>("button:not(:disabled),a[href]") ?? event.currentTargetfocusTarget.focus()}- else restSurface(event.currentTarget)-}}>{children(close, `${id}-label`)}- </div>+ </motion.div></>}-export interface LauncherProps extends Omit<ComponentPropsWithoutRef<"div">, "children" | "id" | "onBeforeToggle" | "onToggle" | "popover"> {+export interface LauncherProps extends Omit<ComponentPropsWithoutRef<"div">, "children" | "id" | "onAnimationStart" | "onBeforeToggle" | "onDrag" | "onDragEnd" | "onDragStart" | "onToggle" | "popover"> {label: stringdiff --git a/source/client/view/structure/desktop/taskbar/system/system-dialogs.tsx b/source/client/view/structure/desktop/taskbar/system/system-dialogs.tsxindex 1102a7e..942b3ef 100644--- a/source/client/view/structure/desktop/taskbar/system/system-dialogs.tsx+++ b/source/client/view/structure/desktop/taskbar/system/system-dialogs.tsx@@ -1,13 +1,15 @@import { type PermissionChoice, type PermissionDialog, type ServerCrashDialog } from "@server/core/dialog-manager"import { ReactTunnel } from "@the-link/react"-import { enterSurface, prepareSurfaceEntrance, restSurface } from "@client/view/appearance/surface-presence"+import { surfacePresencePose, surfacePresenceTransition } from "@client/view/appearance/surface-presence"import { useReducedMotion } from "@libs/react-motion"+import { motion } from "motion/react"import { useEffect, useId, useRef } from "react"import { AuthManagerContext } from "@client/view/contexts"import TaskbarSurface, { taskbarSurfaceClassName } from "../taskbar-surface"import TaskbarButton from "../taskbar-button"import usePromise from "@libs/react-promise"import Alert from "@client/view/components/alert"+import { useAppearance } from "@phreshos/react-ui"/** Taskbar-owned presentation of the system's authoritative dialog queue. */export default function SystemDialogs() {@@ -31,6 +33,7 @@ export default function SystemDialogs() {const description = useId()const reducedMotion = useReducedMotion()+ const transaction = useAppearance().transactionuseEffect(function () {@@ -38,16 +41,10 @@ export default function SystemDialogs() {if (!dialog || !element || element.open) return- prepareSurfaceEntrance(element, reducedMotion)-element.showModal()- enterSurface(element, reducedMotion)-return function () {- restSurface(element)-if (element.open) element.close()}@@ -55,7 +52,7 @@ export default function SystemDialogs() {if (!dialog) return null- return <dialog+ return <motion.dialogref={surface}@@ -67,6 +64,12 @@ export default function SystemDialogs() {aria-describedby={description}+ initial={reducedMotion ? surfacePresencePose.entered : surfacePresencePose.entering}++ animate={surfacePresencePose.entered}++ transition={surfacePresenceTransition(reducedMotion, transaction)}+onCancel={event => event.preventDefault()}className={`${taskbarSurfaceClassName} inset-auto inset-be-[calc(anchor(top)+var(--desktop-gutter))] inset-s-[anchor(center)] w-[min(28rem,calc(100vw-var(--desktop-gutter)*2))] -translate-x-1/2 backdrop:bg-transparent [position-anchor:--desktop-taskbar]`}@@ -83,7 +86,7 @@ export default function SystemDialogs() {</TaskbarSurface>- </dialog>+ </motion.dialog>}function PermissionRequest({ dialog, description, decide }: PermissionRequestProps) {diff --git a/source/client/view/structure/desktop/wallpaper/wallpaper.tsx b/source/client/view/structure/desktop/wallpaper/wallpaper.tsxindex 62125c4..a5c15ac 100644--- a/source/client/view/structure/desktop/wallpaper/wallpaper.tsx+++ b/source/client/view/structure/desktop/wallpaper/wallpaper.tsx@@ -4,7 +4,9 @@ import { ApplicationContext } from "@client/view/contexts"import { useEffect, useEffectEvent, useRef, useState, type ReactNode, type TransitionEvent } from "react"import Loading from "@client/view/components/loading"import { useReady } from "@libs/readiness"-import { useTheme } from "@phreshos/react-ui"+import { useAppearance, useTheme } from "@phreshos/react-ui"+import { useReducedMotion } from "@libs/react-motion"+import { cssEasing } from "@client/view/appearance/motion"const bundledWallpapers = [darkWallpaper, lightWallpaper] as const@@ -30,6 +32,7 @@ export function WallpaperBackground({ file, onReady }: WallpaperBackgroundProps)const application = ApplicationContext.useValue()const theme = useTheme()+ const reducedMotion = useReducedMotion()const desired = file === null? theme === "dark" ? darkWallpaper : lightWallpaper@@ -49,7 +52,7 @@ export function WallpaperBackground({ file, onReady }: WallpaperBackgroundProps)const display = useEffectEvent((source: string) => {const shown = current.current- if (!shown.displayed) {+ if (!shown.displayed || reducedMotion) {setLayers({ displayed: source, incoming: null, switching: false })return}@@ -121,10 +124,18 @@ function WallpaperLayer({ source, visible, onTransitionEnd }: {visible: booleanonTransitionEnd?: (event: TransitionEvent<HTMLDivElement>) => void}) {+ const transaction = useAppearance().transaction+ const reducedMotion = useReducedMotion()+return <divaria-hidden="true"- className={`pointer-events-none absolute inset-0 bg-cover bg-center bg-no-repeat transition-opacity duration-700 ease-out ${visible ? "opacity-100" : "opacity-0"}`}- style={{ backgroundImage: `url(${source})` }}+ className={`pointer-events-none absolute inset-0 bg-cover bg-center bg-no-repeat ${visible ? "opacity-100" : "opacity-0"}`}+ style={{+ backgroundImage: `url(${source})`,+ transitionDuration: reducedMotion ? "0ms" : String(transaction.duration) + "ms",+ transitionTimingFunction: cssEasing(transaction.easing),+ transitionProperty: "opacity"+ }}onTransitionEnd={onTransitionEnd}/>}diff --git a/source/client/view/structure/desktop/windows/snap-preview.tsx b/source/client/view/structure/desktop/windows/snap-preview.tsxindex 327cf7f..a2fadea 100644--- a/source/client/view/structure/desktop/windows/snap-preview.tsx+++ b/source/client/view/structure/desktop/windows/snap-preview.tsx@@ -1,88 +1,41 @@-import { type CSSProperties, useLayoutEffect, useRef, useState } from "react"-import gsap, { motionDuration, motionDurations, motionEase } from "@client/view/appearance/motion"-import { resolveWindowGeometry, resolveWindowValue, windowPaintInsets, type WindowSurfaceSize } from "@client/view/components/window-manager/window-geometry"+import { type CSSProperties } from "react"+import { motion } from "motion/react"+import { windowPaintInsets, type WindowSurfaceSize } from "@client/view/components/window-manager/window-geometry"import { windowPaintInset } from "../geometry"import { type Position, type Size } from "@phreshos/core"-import { Surface } from "@phreshos/react-ui"+import { Surface, useAppearance } from "@phreshos/react-ui"+import { motionTransition } from "@client/view/appearance/motion"+import useWindowGeometryMotion from "./window-geometry-motion"-/** GSAP-owned preview of the placement currently offered by a drag. */+/** Preview of the placement currently offered by a drag. */export default function SnapPreview({ shown, visible, bare, paintSurfaceSize, reducedMotion, zIndex }: SnapPreviewProps) {- const element = useRef<HTMLDivElement>(null)- const firstRender = useRef(true)- const [rendered, setRendered] = useState(shown)+ const transaction = useAppearance().transaction- useLayoutEffect(function () {+ const geometry = useWindowGeometryMotion({+ position: shown.position,+ size: shown.size,+ animation: null,+ immediate: reducedMotion+ })- const preview = element.current- const parent = preview?.offsetParent-- if (!preview || !parent) return-- const parentBounds = parent.getBoundingClientRect()- const shownBounds = preview.getBoundingClientRect()- const current = {- x: shownBounds.left - parentBounds.left,- y: shownBounds.top - parentBounds.top,- width: shownBounds.width,- height: shownBounds.height- }- const target = resolveWindowGeometry(shown.position, shown.size, parentBounds)- const fromOpacity = firstRender.current ? 0 : Number(getComputedStyle(preview).opacity)-- firstRender.current = false-- gsap.killTweensOf(preview)-- if (reducedMotion) {-- gsap.set(preview, { left: target.x, top: target.y, width: target.width, height: target.height, opacity: visible ? 1 : 0 })- setRendered(shown)-- return- }-- const animation = gsap.fromTo(preview, {- left: current.x,- top: current.y,- width: current.width,- height: current.height,- opacity: fromOpacity- }, {- left: target.x,- top: target.y,- width: target.width,- height: target.height,- opacity: visible ? 1 : 0,- duration: motionDuration(motionDurations.snap),- ease: motionEase([0.33, 1, 0.68, 1]),- overwrite: "auto",- onComplete: () => setRendered(shown)- })-- return () => { animation.kill() }-- }, [shown.position.x, shown.position.y, shown.size.width, shown.size.height, visible, reducedMotion])-- return <div- ref={element}+ return <motion.div+ ref={geometry.frame}className="pointer-events-none absolute"- style={{- left: resolveWindowValue(rendered.position.x),- top: resolveWindowValue(rendered.position.y),- width: resolveWindowValue(rendered.size.width),- height: resolveWindowValue(rendered.size.height),- opacity: visible ? 1 : 0,- zIndex- }}+ initial={false}+ animate={{ scale: visible ? 1 : 0.98, opacity: visible ? 1 : 0 }}+ transition={motionTransition(transaction, reducedMotion)}+ style={{ left: 0, top: 0, transformOrigin: "center", zIndex, ...geometry.style }}><Surfacedata-snap-preview-frame- opacity="small"- className={`absolute ${bare ? "inset-0" : ""}`}- style={bare ? undefined : windowPaintInsets(shown.position, shown.size, paintSurfaceSize, windowPaintInset)}+ material={{ opacity: "small" }}+ style={{+ position: "absolute",+ ...(bare ? { inset: 0 } : windowPaintInsets(shown.position, shown.size, paintSurfaceSize, windowPaintInset))+ }}/>- </div>+ </motion.div>}export interface SnapTarget {diff --git a/source/client/view/structure/desktop/windows/window-geometry-motion.ts b/source/client/view/structure/desktop/windows/window-geometry-motion.tsnew file mode 100644index 0000000..bee4e0f--- /dev/null+++ b/source/client/view/structure/desktop/windows/window-geometry-motion.ts@@ -0,0 +1,203 @@+import { resolveWindowGeometry, type WindowRegion } from "@client/view/components/window-manager/window-geometry"+import { type LocalAnimation } from "@client/view/components/desktop-host/local-window"+import { type AppearanceTransaction, type Position, type Size } from "@phreshos/core"+import { animate, useMotionValue, type AnimationPlaybackControls, type MotionStyle } from "motion/react"+import { useLayoutEffect, useRef } from "react"+import { motionTransition } from "@client/view/appearance/motion"+import { useAppearance } from "@phreshos/react-ui"++interface WindowGeometryMotionOptions {+ position: Position+ size: Size+ animation?: LocalAnimation | null+ immediate: boolean+ onComplete?: (revision: number) => void+}++/**+ * One continuous local representation 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, immediate, onComplete }: WindowGeometryMotionOptions) {++ const appearanceTransaction = useAppearance().transaction+ 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 controls = useRef<AnimationPlaybackControls[]>([])+ const target = useRef<WindowRegion | null>(null)+ const gesturing = useRef(false)+ const initialized = useRef(false)+ const values = useRef({ position, size, animation, immediate, onComplete })++ values.current = { position, size, animation, immediate, onComplete }++ function read(): WindowRegion {++ return { x: x.get(), y: y.get(), width: width.get(), height: height.get() }+ }++ function stop() {++ for (const control of controls.current) control.stop()++ controls.current = []+ }++ function set(region: WindowRegion) {++ stop()+ target.current = region+ x.set(region.x)+ y.set(region.y)+ width.set(region.width)+ height.set(region.height)+ }++ function transition(region: WindowRegion, transaction: AppearanceTransaction = appearanceTransaction, complete?: () => void) {++ stop()+ target.current = region++ if (immediate || transaction?.duration === 0 || sameRegion(read(), region)) {++ set(region)+ complete?.()++ return+ }++ const options = motionTransition(transaction)++ controls.current = [+ animate(x, region.x, { ...options, onComplete: complete }),+ animate(y, region.y, options),+ animate(width, region.width, options),+ animate(height, region.height, options)+ ]+ }++ function resolve() {++ const parent = frame.current?.offsetParent++ return parent ? resolveWindowGeometry(values.current.position, values.current.size, parent.getBoundingClientRect()) : null+ }++ 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+ }++ if (target.current && sameRegion(target.current, region)) return++ transition(region, animation?.transaction, revision === undefined ? undefined : () => onComplete?.(revision))++ }, [position.x, position.y, size.width, size.height, animation?.revision, immediate])++ useLayoutEffect(function () {++ const parent = frame.current?.offsetParent++ if (!parent) return++ let bounds = parent.getBoundingClientRect()++ const observer = new ResizeObserver(function () {++ const next = parent.getBoundingClientRect()++ 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(() => stop, [])++ function beginGesture() {++ const parent = frame.current?.offsetParent++ if (!parent) return null++ gesturing.current = true+ stop()+ target.current = null++ return { bounds: parent.getBoundingClientRect(), region: read() }+ }++ function updateGesture(region: WindowRegion) {++ x.set(region.x)+ y.set(region.y)+ width.set(region.width)+ height.set(region.height)+ }++ function finishGesture(region?: WindowRegion) {++ gesturing.current = false++ if (region) transition(region)++ else target.current = read()+ }++ function cancelGesture() {++ gesturing.current = false++ const region = resolve()++ if (region) set(region)+ }++ return {+ frame,+ style: { x, y, width, height } satisfies MotionStyle,+ read,+ beginGesture,+ updateGesture,+ finishGesture,+ cancelGesture+ }+}++function sameRegion(left: WindowRegion, right: WindowRegion) {++ return Math.abs(left.x - right.x) <= 0.5+ && Math.abs(left.y - right.y) <= 0.5+ && Math.abs(left.width - right.width) <= 0.5+ && Math.abs(left.height - right.height) <= 0.5+}diff --git a/source/client/view/structure/desktop/windows/window-header.tsx b/source/client/view/structure/desktop/windows/window-header.tsxindex c14e7e3..4fd8709 100644--- a/source/client/view/structure/desktop/windows/window-header.tsx+++ b/source/client/view/structure/desktop/windows/window-header.tsx@@ -1,5 +1,7 @@-import { ComponentProps, PointerEvent as ReactPointerEvent, ReactNode, useLayoutEffect, useRef, useState } from "react"-import gsap, { motionDuration, motionDurations, motionEase } from "@client/view/appearance/motion"+import { ComponentProps, PointerEvent as ReactPointerEvent, ReactNode, useState } from "react"+import { motion } from "motion/react"+import { motionTransition } from "@client/view/appearance/motion"+import { useAppearance } from "@phreshos/react-ui"const control = {base: { borderColor: "transparent", backgroundColor: "rgba(255, 255, 255, 0.15)", color: "#475569", scale: 1 },@@ -10,43 +12,7 @@ const control = {/** The visible chrome above an ordinary window's content. */export default function WindowHeader({ title, icon, active, whole, reducedMotion, stopping, onGrab, onMinimize, onMaximize, onClose }: WindowHeaderProps) {- const iconElement = useRef<HTMLImageElement>(null)- const titleElement = useRef<HTMLSpanElement>(null)- const [renderedActive, setRenderedActive] = useState(active)-- useLayoutEffect(function () {-- const icon = iconElement.current- const title = titleElement.current-- if (!icon || !title || renderedActive === active) return-- const opacity = active ? 1 : 0.6-- gsap.killTweensOf([icon, title])-- if (reducedMotion) {-- gsap.set([icon, title], { opacity })- setRenderedActive(active)-- return- }-- const timeline = gsap.timeline({- defaults: {- duration: motionDuration(motionDurations.feedback),- ease: motionEase("ease-out"),- overwrite: "auto"- },- onComplete: () => setRenderedActive(active)- })-- timeline.to([icon, title], { opacity }, 0)-- return () => { timeline.kill() }-- }, [active, reducedMotion, renderedActive])+ const transition = motionTransition(useAppearance().transaction, reducedMotion)return <div@@ -58,9 +24,7 @@ export default function WindowHeader({ title, icon, active, whole, reducedMotion>- <img-- ref={iconElement}+ <motion.imgsrc={icon}@@ -70,17 +34,22 @@ export default function WindowHeader({ title, icon, active, whole, reducedMotionclassName="size-4 rounded-sm object-contain"- style={{ opacity: renderedActive ? 1 : 0.6 }}+ initial={false}++ animate={{ opacity: active ? 1 : 0.6 }}++ transition={transition}/>{/* Focus is said on the chrome and nowhere else. Content staysequally legible when another window owns the keyboard. */}- <span- ref={titleElement}+ <motion.spanclassName="truncate text-window-title font-medium"- style={{ opacity: renderedActive ? 1 : 0.6 }}- >{title}</span>+ initial={false}+ animate={{ opacity: active ? 1 : 0.6 }}+ transition={transition}+ >{title}</motion.span><div className="grid shrink-0 grid-flow-col auto-cols-max gap-1" onPointerDown={event => event.stopPropagation()}>@@ -116,8 +85,7 @@ export default function WindowHeader({ title, icon, active, whole, reducedMotion// assistive technology still use the button's native click activation.function Control({ label, danger = false, focusOnPointerDown = true, reducedMotion, children, onClick, ...props }: ControlProps) {- const element = useRef<HTMLButtonElement>(null)- const hovering = useRef(false)+ const [interaction, setInteraction] = useState<"base" | "hover" | "pressed">("base")const hover = danger ? control.danger : control.hover@@ -127,42 +95,28 @@ function Control({ label, danger = false, focusOnPointerDown = true, reducedMotiscale: 0.95}- function react(values: typeof control.base) {-- const button = element.current-- if (!button) return-- gsap.killTweensOf(button)+ const values = interaction === "pressed" ? pressed : interaction === "hover" ? hover : control.base- if (reducedMotion) gsap.set(button, values)+ return <motion.button- else gsap.to(button, {- ...values,- duration: motionDuration(motionDurations.control),- ease: motionEase("ease-out"),- overwrite: "auto"- })- }+ {...props}- return <button+ aria-label={label}- {...props}+ initial={false}- ref={element}+ animate={values}- aria-label={label}+ transition={motionTransition(useAppearance().transaction, reducedMotion)}onPointerEnter={() => {- hovering.current = true- react(hover)+ setInteraction("hover")}}onPointerLeave={() => {- hovering.current = false- react(control.base)+ setInteraction("base")}}onPointerDown={event => {@@ -171,7 +125,7 @@ function Control({ label, danger = false, focusOnPointerDown = true, reducedMotiif (event.button !== 0) return- react(pressed)+ setInteraction("pressed")if (focusOnPointerDown) event.currentTarget.focus({ preventScroll: true })@@ -182,18 +136,18 @@ function Control({ label, danger = false, focusOnPointerDown = true, reducedMotionClick?.()}}- onPointerUp={() => react(hovering.current ? hover : control.base)}+ onPointerUp={() => setInteraction("hover")}- onPointerCancel={() => react(hovering.current ? hover : control.base)}+ onPointerCancel={() => setInteraction("base")}onKeyDown={event => {- if (event.key === "Enter" || event.key === " ") react(pressed)+ if (event.key === "Enter" || event.key === " ") setInteraction("pressed")}}onKeyUp={event => {- if (event.key === "Enter" || event.key === " ") react(hovering.current ? hover : control.base)+ if (event.key === "Enter" || event.key === " ") setInteraction("base")}}onClick={event => {@@ -213,7 +167,7 @@ function Control({ label, danger = false, focusOnPointerDown = true, reducedMoti</svg>- </button>+ </motion.button>}interface WindowHeaderProps {@@ -239,7 +193,7 @@ interface WindowHeaderProps {onClose?: () => void}-interface ControlProps extends Omit<ComponentProps<"button">, "onClick"> {+interface ControlProps extends Omit<ComponentProps<"button">, "onAnimationStart" | "onClick" | "onDrag" | "onDragEnd" | "onDragStart"> {label: stringdiff --git a/source/client/view/structure/desktop/windows/window-surface.tsx b/source/client/view/structure/desktop/windows/window-surface.tsxindex 7dbec33..1dad60a 100644--- a/source/client/view/structure/desktop/windows/window-surface.tsx+++ b/source/client/view/structure/desktop/windows/window-surface.tsx@@ -1,86 +1,52 @@import { useReducedMotion } from "@libs/react-motion"import { Surface } from "@phreshos/react-ui"-import { useLayoutEffect, useRef } from "react"+import { useLayoutEffect, useRef, useState } from "react"+import { motion } from "motion/react"import { type LocalSurfaceState } from "@client/view/components/desktop-host/local-window"-import gsap from "@client/view/appearance/motion"-import { enterSurface, leaveSurface, prepareSurfaceEntrance, restSurface } from "@client/view/appearance/surface-presence"+import { surfacePresencePose, surfacePresenceTransition } from "@client/view/appearance/surface-presence"-/** Projects one representation-local target and animates explicit replacements. */+/** Projects one representation-local Surface without animating its material host. */export default function WindowSurface({ state, onComplete }: WindowSurfaceProps) {const { transition, visible } = state-- const element = useRef<HTMLDivElement>(null)-- const firstRender = useRef(true)-const reducedMotion = useReducedMotion()+ const revision = transition?.revision+ const transaction = transition?.transaction+ const animated = revision !== undefined && transaction !== undefined+ const [hidden, setHidden] = useState(!visible)+ const completed = useRef<number | null>(null)useLayoutEffect(function () {- const surface = element.current-- if (!surface) return-- const revision = transition?.revision ?? null-- const changed = revision !== null-- const initial = firstRender.current-- firstRender.current = false-- const transaction = transition?.transaction-- // Desktop owns presence of the whole Surface; React UI owns its- // material. The Program's transaction controls the shared entrance- // pose without reaching into paint, border or backdrop layers.- if (!transaction || !changed) {-- restSurface(surface)-- gsap.set(surface, { visibility: visible ? "visible" : "hidden" })+ if (visible) setHidden(false)- return- }+ else if (!animated || reducedMotion) setHidden(true)- const hidden = getComputedStyle(surface).visibility === "hidden"+ }, [visible, animated, reducedMotion])- if (visible && (initial || hidden)) prepareSurfaceEntrance(surface, reducedMotion)+ function finish() {- gsap.set(surface, { visibility: "visible" })+ if (revision === undefined || completed.current === revision) return- const complete = function () {+ completed.current = revision- if (!visible) gsap.set(surface, { visibility: "hidden" })+ if (!visible) setHidden(true)- onComplete(revision!)- }-- const animation = visible-- ? enterSurface(surface, reducedMotion, { ...transaction, onComplete: complete })-- : leaveSurface(surface, reducedMotion, { ...transaction, onComplete: complete })-- return function () {-- animation?.kill()- }-- }, [reducedMotion, transition?.revision, visible])-- return <Surface-- ref={element}-- data-window-surface-- aria-hidden="true"+ onComplete(revision)+ }+ return <motion.div+ initial={animated && visible && !reducedMotion ? surfacePresencePose.entering : surfacePresencePose.entered}+ animate={visible ? surfacePresencePose.entered : surfacePresencePose.entering}+ transition={animated+ ? surfacePresenceTransition(reducedMotion, transaction)+ : { duration: 0 }}+ onAnimationComplete={finish}className="pointer-events-none absolute inset-0"-- />+ style={{ visibility: !visible && hidden ? "hidden" : "visible" }}+ >+ <Surface aria-hidden="true" style={{ position: "absolute", inset: 0 }} />+ </motion.div>}interface WindowSurfaceProps {diff --git a/source/client/view/structure/desktop/windows/window.tsx b/source/client/view/structure/desktop/windows/window.tsxindex d20adc6..9dcff1d 100644--- a/source/client/view/structure/desktop/windows/window.tsx+++ b/source/client/view/structure/desktop/windows/window.tsx@@ -1,34 +1,35 @@-import { ComponentProps, PointerEvent as ReactPointerEvent, ReactNode, useLayoutEffect, useRef, useState } from "react"+import { ComponentProps, PointerEvent as ReactPointerEvent, ReactNode, useEffect, useLayoutEffect, useRef, useState } from "react"import { useReducedMotion } from "@libs/react-motion"-import { enterSurface, leaveSurface, prepareSurfaceEntrance, restSurface } from "@client/view/appearance/surface-presence"+import { surfacePresencePose, surfacePresenceTransition } from "@client/view/appearance/surface-presence"import WindowPanel from "./window-panel"-import { absoluteWindowGeometry, resolveWindowGeometry, resolveWindowValue, wholeWindowGeometry, windowPaintInsets, type WindowRegion, type WindowSurfaceSize } from "@client/view/components/window-manager/window-geometry"-import { type Position, type Size, type WindowGeometry } from "@phreshos/core"+import { absoluteWindowGeometry, resolveWindowGeometry, wholeWindowGeometry, windowPaintInsets, type WindowRegion, type WindowSurfaceSize } from "@client/view/components/window-manager/window-geometry"+import { type Position, type Size } from "@phreshos/core"import WindowHeader from "./window-header"import WindowSurface from "./window-surface"import { type LocalAnimation, type LocalSurfaceState } from "@client/view/components/desktop-host/local-window"import { type LocalGeometryReader } from "@client/view/components/window-manager/local-windows"-import gsap, { motionDuration, motionDurations, motionEase } from "@client/view/appearance/motion"+import { motion } from "motion/react"+import { motionTransition } from "@client/view/appearance/motion"+import { useAppearance } from "@phreshos/react-ui"import SnapPreview, { type SnapTarget } from "./snap-preview"import { windowPaintInset } from "../geometry"+import useWindowGeometryMotion from "./window-geometry-motion"/*** A window: a pure function of the record it is given. Every render* declares the whole target geometry from props — a float as left/top- * pixels, a tile as its relative form. GSAP interpolates only the local+ * pixels, a tile as its relative form. Motion interpolates only the local* representation between targets; the record remains the truth and a* refreshed page renders that truth directly.*- * A gesture is state, not a side channel: while one runs, the render- * derives from the gesture's rectangle instead of the record — movement- * rides a transform above the grabbed origin, interpolation pauses — and- * release reports the outcome (onMove or onResize with resting pixels —+ * One set of Motion values owns the visible pixel geometry from rest,+ * through a gesture, and into the next target. Release reports the outcome+ * (onMove or onResize with resting pixels —* a resize carrying an origin only when the edge dragged moved one —* onSnap with the shares a zone names) and drops the gesture in the same* batch the record updates, so nothing jumps.*- * GSAP owns every structural interpolation: frame geometry, local Surface- * replacement, and the scale and drift of presence. It never owns state.+ * Motion owns every local interpolation, never the authoritative record.** The chrome uses the shared system material. Content currently uses the* plain WindowPanel test. The close control requests — the window leaves only when the truth@@ -47,26 +48,27 @@ const edges: { edge: WindowEdge, className: string }[] = []const surfacePose = {- resting: { scale: 1, y: 0 },- minimized: { scale: 0.86, y: 28 },- closing: { scale: 0.86, y: 12 }+ resting: { scale: 1, y: 0, opacity: 1 },+ minimized: { scale: 0.86, y: 28, opacity: 0 },+ closing: { scale: 0.86, y: 12, opacity: 0 }}export default function ({ title, icon, children, onClose, onClosed, onMinimize, onMaximize, onActivate, onUnavailable, onMove, onResize, onSnap, onLocalAnimationComplete, onLocalRepresentation, onFocusCapture, active = false, bare = false, closing = false, stopping = false, minimized = false, animateEntrance = true, position = { x: 0, y: 0 }, size = { width: 520, height: 340 }, localSurface, geometryAnimation, minimizeAnimation, paintSurfaceSize = { width: 0, height: 0 }, minWidth = 260, minHeight = 160, className, style, ...props }: WindowProps) {- const frame = useRef<HTMLDivElement>(null)-- const surfaceElement = useRef<HTMLDivElement>(null)-const reducedMotion = useReducedMotion()+ const appearanceTransaction = useAppearance().transaction- const [gesture, setGesture] = useState<Gesture | null>(null)+ const geometryMotion = useWindowGeometryMotion({+ position,+ size,+ animation: geometryAnimation,+ immediate: bare || reducedMotion,+ onComplete: revision => onLocalAnimationComplete?.("geometry", revision)+ })- const [renderedGeometry, setRenderedGeometry] = useState<WindowGeometry>({ position, size })+ const frame = geometryMotion.frame- const morphStart = useRef<WindowRegion | null>(null)-- const morphRevision = useRef(0)+ const [gesture, setGesture] = useState<Gesture | null>(null)useLayoutEffect(function () {@@ -74,18 +76,10 @@ export default function ({ title, icon, children, onClose, onClosed, onMinimize,const read: LocalGeometryReader = function () {- const element = frame.current-- const parent = element?.offsetParent-- if (!element || !parent) return { position, size }-- const shown = element.getBoundingClientRect()-- const surface = parent.getBoundingClientRect()+ const shown = geometryMotion.read()return {- position: { x: shown.left - surface.left, y: shown.top - surface.top },+ position: { x: shown.x, y: shown.y },size: { width: shown.width, height: shown.height }}}@@ -96,126 +90,6 @@ export default function ({ title, icon, children, onClose, onClosed, onMinimize,}, [onLocalRepresentation, position, size])- useLayoutEffect(function () {-- const element = frame.current-- const parent = element?.offsetParent-- if (!element || !parent || gesture) return-- if (sameGeometry(renderedGeometry, { position, size })) {-- if (geometryAnimation) onLocalAnimationComplete?.("geometry", geometryAnimation.revision)-- return- }-- const parentBounds = parent.getBoundingClientRect()- const shown = element.getBoundingClientRect()- const current = {- x: shown.left - parentBounds.left,- y: shown.top - parentBounds.top,- width: shown.width,- height: shown.height- }- const target = resolveWindowGeometry(position, size, parentBounds)- const transaction = geometryAnimation?.transaction- const duration = transaction?.duration ?? motionDurations.geometry-- gsap.killTweensOf(element)-- const complete = function () {-- setRenderedGeometry({ position, size })-- if (geometryAnimation) onLocalAnimationComplete?.("geometry", geometryAnimation.revision)- }-- if (bare || reducedMotion || duration === 0 || sameRegion(current, target)) {-- gsap.set(element, { left: target.x, top: target.y, width: target.width, height: target.height, transform: "none" })- complete()-- return- }-- // Lay out the authoritative target once, then animate only the visual- // difference. Reflowing an iframe-sized box on every animation frame- // causes the small hitch this transition is meant to hide.- gsap.set(element, {- left: target.x,- top: target.y,- width: target.width,- height: target.height,- transformOrigin: "0 0"- })-- const animation = gsap.fromTo(element, {- x: current.x - target.x,- y: current.y - target.y,- scaleX: current.width / target.width,- scaleY: current.height / target.height- }, {- x: 0,- y: 0,- scaleX: 1,- scaleY: 1,- duration: motionDuration(duration),- ease: transaction ? motionEase(transaction.easing) : motionEase([0.33, 1, 0.68, 1]),- force3D: true,- overwrite: "auto",- onComplete: function () {-- gsap.set(element, { transform: "none", transformOrigin: "" })- complete()- }- })-- return function () {-- const held = element.getBoundingClientRect()- const bounds = parent.getBoundingClientRect()-- animation.kill()-- gsap.set(element, {- left: held.left - bounds.left,- top: held.top - bounds.top,- width: held.width,- height: held.height,- transform: "none"- })- }-- }, [position.x, position.y, size.width, size.height, geometryAnimation?.revision, reducedMotion, bare, gesture !== null])-- useLayoutEffect(function () {-- const element = frame.current- const from = morphStart.current-- if (!element || !from || gesture?.morph == null || reducedMotion) return-- const animation = gsap.fromTo(element, {- left: from.x,- top: from.y,- width: from.width,- height: from.height- }, {- left: gesture.origin.x,- top: gesture.origin.y,- width: gesture.current.width,- height: gesture.current.height,- duration: motionDuration(motionDurations.morph),- ease: motionEase([0.33, 1, 0.68, 1]),- overwrite: "auto"- })-- return () => { animation.kill() }-- }, [gesture?.morph, reducedMotion])-const closureCompleted = useRef(false)function completeClosure() {@@ -236,181 +110,77 @@ export default function ({ title, icon, children, onClose, onClosed, onMinimize,// this is the interface recognising a size it offered to set.const whole = wholeWindowGeometry(position, size)- // Presence: a newly created window enters, while a window inherited- // when its desktop mounts is already here and renders at rest. A full- // page refresh remounts elements, not processes, and must not make all- // restored windows look newly opened.- //- // Bare, there is no entrance. Motion is a visual effect like the- // surface, and `under` and `over` are the layers where- // the system paints nothing — so what would scale and drift here is- // the program's own content, which reads as the program stumbling- // rather than as a window opening. It showed on every refresh,- // because a refresh mounts every window and a mount is a birth.- useLayoutEffect(function () {-- if (bare) return-- if (minimized) {-- gsap.set(surfaceElement.current, { scale: reducedMotion ? 1 : 0.86, y: reducedMotion ? 0 : 28, visibility: "hidden" })-- return- }-- if (!animateEntrance) {-- restSurface(surfaceElement.current)-- gsap.set(surfaceElement.current, { visibility: "visible" })-- return- }-- prepareSurfaceEntrance(surfaceElement.current, reducedMotion)-- gsap.set(surfaceElement.current, { visibility: "visible" })-- const animation = enterSurface(surfaceElement.current, reducedMotion)-- return () => { animation?.kill() }-- // Presence at birth reads the mount's own values once.- }, [])-- // A preference change takes effect immediately. Any automatic travel- // already in progress is ended at its truthful final representation;- // closing still answers its completion handshake.- useLayoutEffect(function () {-- if (!surfaceElement.current) return-- // A hidden window can silently prepare the pose that a future- // restore will animate from if the preference has been relaxed.- if (!reducedMotion) {+ const [presenceHidden, setPresenceHidden] = useState(minimized)- if (minimized) gsap.set(surfaceElement.current, { ...surfacePose.minimized, visibility: "hidden" })-- return- }-- gsap.killTweensOf(surfaceElement.current)-- gsap.set(surfaceElement.current, { ...surfacePose.resting, visibility: minimized || closing ? "hidden" : "visible" })-- if (closing) {-- onUnavailable?.("close")-- completeClosure()- }-- else if (minimized) onUnavailable?.("minimize")-- }, [reducedMotion])-- // Minimising drifts toward the taskbar; restoring rises back.- const arrived = useRef(false)+ const minimizeTransaction = minimizeAnimation?.transactionuseLayoutEffect(function () {- if (!arrived.current) {+ if (!minimized) setPresenceHidden(false)- arrived.current = true+ else if (reducedMotion) setPresenceHidden(true)- return- }+ }, [minimized, reducedMotion])- if (!surfaceElement.current) return+ useEffect(function () {if (minimized) onUnavailable?.("minimize")- if (bare) {-- const revision = minimizeAnimation?.revision- const transaction = minimizeAnimation?.transaction+ }, [minimized])- if (!transaction) {+ useEffect(function () {- restSurface(surfaceElement.current)- gsap.set(surfaceElement.current, { visibility: minimized ? "hidden" : "visible" })-- if (revision !== undefined) onLocalAnimationComplete?.("minimize", revision)-- return- }+ if (!closing) return- if (!minimized) {-- prepareSurfaceEntrance(surfaceElement.current, reducedMotion)- gsap.set(surfaceElement.current, { visibility: "visible" })- }-- const complete = function () {-- if (minimized) gsap.set(surfaceElement.current, { visibility: "hidden" })-- onLocalAnimationComplete?.("minimize", revision!)- }-- const animation = minimized- ? leaveSurface(surfaceElement.current, reducedMotion, { ...transaction, onComplete: complete })- : enterSurface(surfaceElement.current, reducedMotion, { ...transaction, onComplete: complete })+ onUnavailable?.("close")- return () => { animation?.kill() }- }+ // Bare layers have no system presence animation, and reduced motion+ // has no duration to wait for. The close handshake still completes.+ if (bare || reducedMotion) completeClosure()- if (reducedMotion) {+ }, [closing, bare, reducedMotion])- gsap.set(surfaceElement.current, { ...surfacePose.resting, visibility: minimized ? "hidden" : "visible" })+ useEffect(function () {- return- }+ const revision = minimizeAnimation?.revision- // Presence is scale and drift, never opacity, so the material and its- // content remain visually stable throughout the movement. Going away- // is a departure toward the taskbar; hiding happens only at the end.- if (!minimized) gsap.set(surfaceElement.current, { visibility: "visible" })+ if (!bare || revision === undefined || minimizeTransaction && !reducedMotion) return- const animation = minimized+ onLocalAnimationComplete?.("minimize", revision)- ? gsap.to(surfaceElement.current, { ...surfacePose.minimized, duration: motionDuration(motionDurations.minimize), ease: "power3.in", overwrite: "auto", onComplete: () => gsap.set(surfaceElement.current, { visibility: "hidden" }) })+ }, [bare, minimizeAnimation?.revision, reducedMotion])- : gsap.to(surfaceElement.current, { ...surfacePose.resting, duration: motionDuration(motionDurations.restore), ease: "power3.out", overwrite: "auto" })+ const initialPresence = bare || reducedMotion || !animateEntrance+ ? surfacePresencePose.entered+ : surfacePresencePose.entering- return () => { animation.kill() }+ const presencePose = closing && !bare+ ? surfacePose.closing+ : minimized+ ? bare ? surfacePresencePose.entering : surfacePose.minimized+ : surfacePose.resting- }, [minimized, minimizeAnimation?.revision])+ const presenceTransition = reducedMotion+ ? { duration: 0 }+ : bare+ ? minimizeTransaction+ ? surfacePresenceTransition(false, minimizeTransaction)+ : { duration: 0 }+ : motionTransition(closing ? appearanceTransaction : minimizeTransaction ?? appearanceTransaction)- // Closing is a handshake: the exit plays, onClosed reports the- // element may be unmounted.- useLayoutEffect(function () {+ function completePresence() {- if (!closing || !surfaceElement.current) return+ if (closing && !bare) completeClosure()- onUnavailable?.("close")+ if (minimized) setPresenceHidden(true)- // Bare, there is no exit to play — but the handshake still has- // to be answered, or the desktop keeps the leaving record- // forever waiting for an animation that never runs.- if (bare || reducedMotion) {+ const revision = minimizeAnimation?.revision- completeClosure()+ if (bare && revision !== undefined && minimizeTransaction && !reducedMotion) {- return+ onLocalAnimationComplete?.("minimize", revision)}-- const animation = gsap.to(surfaceElement.current, {- ...surfacePose.closing,- duration: motionDuration(motionDurations.close),- ease: "power2.in",- overwrite: "auto",- onComplete: completeClosure- })-- return () => { animation.kill() }-- }, [closing])+ }function grab(event: ReactPointerEvent<HTMLElement>, edge: WindowEdge | null) {@@ -423,29 +193,18 @@ export default function ({ title, icon, children, onClose, onClosed, onMinimize,handle.setPointerCapture(event.pointerId)- const parent = frame.current?.offsetParent+ const started = geometryMotion.beginGesture()- const bounds = parent?.getBoundingClientRect()+ if (!started) return- if (!frame.current || !parent || !bounds) return+ const { bounds } = started- // The grabbed origin is measured, not assumed: grabbing a window- // mid-transition holds it exactly where the eye sees it.- const rect = frame.current.getBoundingClientRect()-- let origin: WindowRegion = { x: rect.left - bounds.left, y: rect.top - bounds.top, width: rect.width, height: rect.height }+ // The Motion values are the current visible representation, including+ // a geometry animation interrupted by this press.+ let origin: WindowRegion = started.regionlet current: WindowRegion = { ...origin }- gsap.killTweensOf(frame.current)-- gsap.set(frame.current, { left: origin.x, top: origin.y, width: origin.width, height: origin.height, transform: "none" })-- setRenderedGeometry({- position: { x: origin.x, y: origin.y },- size: { width: origin.width, height: origin.height }- })-if (geometryAnimation) onLocalAnimationComplete?.("geometry", geometryAnimation.revision)// Pulling a shared window out of its placement belongs to the@@ -456,8 +215,6 @@ export default function ({ title, icon, children, onClose, onClosed, onMinimize,let moved = false- let morph: number | null = null-let zone: Snap | null = nulllet shown: Snap | null = null@@ -477,7 +234,7 @@ export default function ({ title, icon, children, onClose, onClosed, onMinimize,renderFrame = 0- setGesture({ origin, current, zone, shown, morph })+ setGesture({ origin, current, zone, shown })})}@@ -543,23 +300,8 @@ export default function ({ title, icon, children, onClose, onClosed, onMinimize,onMove?.(origin.x, origin.y)- // The shrink to floating size glides while the pointer- // stays live: a brief morph phase transitions the body,- // never the transform — and it must survive the moves- // that arrive while it plays.- morphStart.current = { ...current }-- morph = reducedMotion ? null : ++morphRevision.current-- if (morph !== null) setTimeout(() => {-- morph = null-- setGesture(active => active && { ...active, morph: null })-- }, 220)-- setGesture({ origin, current, zone, shown, morph })+ geometryMotion.updateGesture(current)+ setGesture({ origin, current, zone, shown })return}@@ -598,6 +340,7 @@ export default function ({ title, icon, children, onClose, onClosed, onMinimize,}}+ geometryMotion.updateGesture(current)renderGesture()}@@ -615,6 +358,7 @@ export default function ({ title, icon, children, onClose, onClosed, onMinimize,// nothing: the render returns to the tile it never left.if (restoring) {+ geometryMotion.finishGesture()setGesture(null)return@@ -625,10 +369,16 @@ export default function ({ title, icon, children, onClose, onClosed, onMinimize,// The outcome and the gesture's end land in one batch: the// record updates as the gesture stops overriding it, so the// frame never shows a stale in-between.- if (term) onSnap?.(term.position, term.size)+ if (term) {++ geometryMotion.finishGesture(resolveWindowGeometry(term.position, term.size, bounds))+ onSnap?.(term.position, term.size)+ }else if (moved && motion.type === "pointerup") {+ geometryMotion.finishGesture()+if (edge === null) onMove?.(current.x, current.y)// Only the west and north edges move the origin. A drag@@ -639,15 +389,9 @@ export default function ({ title, icon, children, onClose, onClosed, onMinimize,}- if (moved && motion.type === "pointerup") {-- setRenderedGeometry({- position: { x: current.x, y: current.y },- size: { width: current.width, height: current.height }- })- }+ else if (motion.type === "pointercancel") geometryMotion.cancelGesture()- else if (motion.type === "pointercancel") setRenderedGeometry({ position, size })+ else geometryMotion.finishGesture()setGesture(null)}@@ -658,32 +402,11 @@ export default function ({ title, icon, children, onClose, onClosed, onMinimize,handle.addEventListener("pointercancel", release)- setGesture({ origin, current, zone, shown, morph: null })+ setGesture({ origin, current, zone, shown })}// ------------------------------------------------------------ render- // The geometry, declared whole every render: the gesture's rectangle- // while one runs — movement as a transform above the grabbed origin,- // otherwise the last settled representation. GSAP moves that stable- // representation to each new authoritative target.- const geometry = gesture-- ? { left: gesture.origin.x, top: gesture.origin.y, width: gesture.current.width, height: gesture.current.height, transform: `translate(${gesture.current.x - gesture.origin.x}px, ${gesture.current.y - gesture.origin.y}px)` }-- : {-- left: resolveWindowValue(renderedGeometry.position.x),-- top: resolveWindowValue(renderedGeometry.position.y),-- width: resolveWindowValue(renderedGeometry.size.width),-- height: resolveWindowValue(renderedGeometry.size.height),-- transform: "none"- }-const paintedInsets = windowPaintInsets(position, size, paintSurfaceSize, windowPaintInset, gesture?.current)return <>@@ -698,7 +421,7 @@ export default function ({ title, icon, children, onClose, onClosed, onMinimize,zIndex={style?.zIndex}/>}- <div+ <motion.divref={frame}@@ -716,7 +439,7 @@ export default function ({ title, icon, children, onClose, onClosed, onMinimize,className={`absolute ${minimized || closing ? "pointer-events-none" : "pointer-events-auto"} ${className ?? ""}`}- style={{ ...geometry, ...style }}+ style={{ ...style, left: 0, top: 0, ...geometryMotion.style }}{...props}@@ -734,7 +457,15 @@ export default function ({ title, icon, children, onClose, onClosed, onMinimize,Bare, there is no difference: the frame fills the box, sothe window is exactly as large as it asked to be and itsboundaries are the ones its own content draws. */}- {bare ? <div data-window-container ref={surfaceElement} className="absolute isolate inset-0 grid grid-rows-1">+ {bare ? <motion.div+ data-window-container+ initial={initialPresence}+ animate={presencePose}+ transition={presenceTransition}+ onAnimationComplete={completePresence}+ className="absolute isolate inset-0 grid grid-rows-1"+ style={{ visibility: minimized && presenceHidden ? "hidden" : "visible" }}+ >{/* A bare Client controls its own host surface, separate fromits content and without the header/content Panel shell. */}@@ -742,11 +473,16 @@ export default function ({ title, icon, children, onClose, onClosed, onMinimize,<div data-window-content className="relative min-h-0">{children}</div>- </div> : <WindowPanel+ </motion.div> : <motion.divdata-window-container- ref={surfaceElement}- style={paintedInsets}- className="absolute"+ initial={initialPresence}+ animate={presencePose}+ transition={presenceTransition}+ onAnimationComplete={completePresence}+ style={{ position: "absolute", visibility: minimized && presenceHidden ? "hidden" : "visible", ...paintedInsets }}+ >+ <WindowPanel+ style={{ position: "absolute", inset: 0 }}header={<WindowHeadertitle={title}@@ -770,7 +506,8 @@ export default function ({ title, icon, children, onClose, onClosed, onMinimize,stopping={stopping || closing}/>}- >{children}</WindowPanel>}+ >{children}</WindowPanel>+ </motion.div>}{!bare && edges.map(handle => <div@@ -782,7 +519,7 @@ export default function ({ title, icon, children, onClose, onClosed, onMinimize,/>)}- </div>+ </motion.div></>}@@ -791,7 +528,7 @@ type WindowEdge = "n" | "s" | "e" | "w" | "ne" | "nw" | "se" | "sw"type Snap = SnapTarget-interface WindowProps extends Omit<ComponentProps<"div">, "title"> {+interface WindowProps extends Omit<ComponentProps<"div">, "onAnimationStart" | "onDrag" | "onDragEnd" | "onDragStart" | "title"> {title?: ReactNode@@ -873,22 +610,4 @@ interface Gesture {zone: Snap | nullshown: Snap | null-- morph: number | null-}--function sameGeometry(left: WindowGeometry, right: WindowGeometry) {-- return left.position.x === right.position.x- && left.position.y === right.position.y- && left.size.width === right.size.width- && left.size.height === right.size.height-}--function sameRegion(left: WindowRegion, right: WindowRegion) {-- return Math.abs(left.x - right.x) <= 0.5- && Math.abs(left.y - right.y) <= 0.5- && Math.abs(left.width - right.width) <= 0.5- && Math.abs(left.height - right.height) <= 0.5}diff --git a/source/client/view/structure/structure.tsx b/source/client/view/structure/structure.tsxindex 39176e5..164807b 100644--- a/source/client/view/structure/structure.tsx+++ b/source/client/view/structure/structure.tsx@@ -2,7 +2,7 @@ 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 { AppearanceProvider, useResolveTheme } from "@phreshos/react-ui"+import { AppearanceProvider, useThemedValue } from "@phreshos/react-ui"import Loading from "../components/loading"import Alert from "../components/alert"import { ApplicationContext, LinkManagerContext } from "../contexts"@@ -12,6 +12,7 @@ import Authentication from "./authentication/authentication"import { useCallback, useEffect, useState } from "react"import Readiness, { useReady } from "@libs/readiness"import { defaultAppearance, type DesktopPreferencesUpdate } from "@phreshos/core"+import { cssEasing } from "../appearance/motion"const startupRequirements = ["connection", "session", "wallpaper"] as const@@ -27,12 +28,15 @@ export default function () {aria-hidden={pending.length === 0}- className={pending.length- ? "opacity-100"- : "pointer-events-none opacity-0 transition-opacity duration-200 ease-out"}- style={{ backgroundColor: defaultAppearance.colors.background.light }}+ className={pending.length ? "opacity-100" : "pointer-events-none opacity-0"}+ style={{+ backgroundColor: defaultAppearance.colors.light.background,+ transitionDuration: String(defaultAppearance.transaction.duration) + "ms",+ transitionTimingFunction: cssEasing(defaultAppearance.transaction.easing),+ transitionProperty: "opacity"+ }}/>}</Readiness.Pending>@@ -132,7 +136,7 @@ function ConnectedDesktop({ linkManager }: { linkManager: LinkManager }) {function ConnectedAppearance({ children }: { children: React.ReactNode }) {- const background = useResolveTheme(LinkManagerContext.useValue().appearance.value.colors.background)+ const background = useThemedValue(LinkManagerContext.useValue().appearance.value.colors).backgroundreturn <div className="grid min-h-0" style={{ backgroundColor: background }}>{children}</div>}diff --git a/source/server/core/appearance-manager.ts b/source/server/core/appearance-manager.tsindex f812031..2442f32 100644--- a/source/server/core/appearance-manager.ts+++ b/source/server/core/appearance-manager.ts@@ -31,27 +31,45 @@ const shadowSchema = z.strictObject({opacity: bounded(appearanceLimits.shadow.opacity)})+const easingSchema = z.union([+ z.enum(["linear", "ease", "ease-in", "ease-out", "ease-in-out"]),+ z.tuple([+ z.number().min(0).max(1),+ z.number(),+ z.number().min(0).max(1),+ z.number()+ ])+])++const transactionSchema = z.strictObject({+ duration: bounded(appearanceLimits.transaction.duration),+ easing: easingSchema+})++const colorsSchema = z.strictObject({+ background: z.string().min(1),+ foreground: z.string().min(1),+ primary: z.string().min(1),+ secondary: z.string().min(1),+ success: z.string().min(1),+ warning: z.string().min(1),+ danger: z.string().min(1),+ info: z.string().min(1)+})+/** The sole schema for authoritative System Appearance state. */export const appearanceSchema: z.ZodType<Appearance> = z.strictObject({- colors: z.strictObject({- background: themed(z.string().min(1)),- foreground: themed(z.string().min(1)),- primary: themed(z.string().min(1)),- secondary: themed(z.string().min(1)),- success: themed(z.string().min(1)),- warning: themed(z.string().min(1)),- danger: themed(z.string().min(1)),- info: themed(z.string().min(1))- }),- spacing: shared(bounded(appearanceLimits.spacing)),- radius: shared(bounded(appearanceLimits.radius)),+ colors: themed(colorsSchema),+ spacing: bounded(appearanceLimits.spacing),+ radius: bounded(appearanceLimits.radius),shadow: themed(shadowSchema),material: themed(materialSchema),+ transaction: transactionSchema,signInWallpaper: themed(wallpaperSchema),desktopWallpaper: themed(wallpaperSchema)})-const properties = Object.keys(defaultAppearance) as (keyof Appearance)[]+const storageKey = "appearance"/** Durable, complete Appearance state owned by Server Core. */export default class AppearanceManager {@@ -62,19 +80,10 @@ export default class AppearanceManager {) { }public static async open(store: Keyv, uploads: UploadManager) {- const entries = await Promise.all(properties.map(async property => ({- property,- value: await store.get(`appearance:${property}`)- })))- const stored = Object.fromEntries(entries.map(({ property, value }) => [- property,- value === undefined ? defaultAppearance[property] : value- ]))- const appearance = createAppearanceSnapshot(appearanceSchema.parse(stored))-- await Promise.all(entries- .filter(({ value }) => value === undefined)- .map(({ property }) => store.set(`appearance:${property}`, appearance[property])))+ const stored = await store.get(storageKey)+ const appearance = createAppearanceSnapshot(appearanceSchema.parse(stored ?? defaultAppearance))++ if (stored === undefined) await store.set(storageKey, appearance)return new AppearanceManager(store, uploads, appearance)}@@ -89,7 +98,7 @@ export default class AppearanceManager {this.validateWallpaper(appearance.desktopWallpaper.light)this.validateWallpaper(appearance.desktopWallpaper.dark)- await Promise.all(properties.map(property => storeProperty(this.store, property, appearance[property])))+ await this.store.set(storageKey, appearance)this.current = appearancereturn appearance@@ -102,10 +111,6 @@ export default class AppearanceManager {}}-function shared<Schema extends z.ZodType>(schema: Schema) {- return z.strictObject({ light: schema })-}-function themed<Schema extends z.ZodType>(schema: Schema) {return z.strictObject({ light: schema, dark: schema })}@@ -113,7 +118,3 @@ function themed<Schema extends z.ZodType>(schema: Schema) {function bounded(range: AppearanceRange) {return z.number().min(range.minimum).max(range.maximum)}--function storeProperty(store: Keyv, property: keyof Appearance, value: Appearance[keyof Appearance]) {- return store.set(`appearance:${property}`, value)-}