An open-source, self-hosted system for apps built with web technologies.
The Desktop keeps what was chosen apart from what it resolves to, and announces each change on its own
zohayrslilehd18a4b51f2f5
diff --git a/source/client/core/link-manager/desktop-preferences-state.ts b/source/client/core/link-manager/desktop-preferences-state.tsindex 54fa8db..aeecf13 100644--- a/source/client/core/link-manager/desktop-preferences-state.ts+++ b/source/client/core/link-manager/desktop-preferences-state.ts@@ -1,31 +1,39 @@-import { type DesktopPreferences } from "@phreshos/core"+import { type DesktopPreferences, type ResolvedDesktopPreferences } from "@phreshos/core"import { Tunnel } from "@the-link/core"-/** Complete effective preferences owned by one browser Desktop. */+/** What one browser Desktop's owner chose, and what it resolves to; each announces its own change. */export default class DesktopPreferencesState {public readonly tunnel = new Tunnel()- public constructor(private current: DesktopPreferences) {}+ public constructor(private chosen: DesktopPreferences, private current: ResolvedDesktopPreferences) {}- public get value() {+ public get preferences() {++ return this.chosen+ }++ public get resolved() {return this.current}- public async update(preferences: DesktopPreferences) {+ public async update(preferences: DesktopPreferences, resolved: ResolvedDesktopPreferences) {- if (samePreferences(this.current, preferences)) return+ const changed = !samePreferences(this.chosen, preferences)+ const changedResolved = !samePreferences(this.current, resolved)- this.current = preferences+ this.chosen = preferences+ this.current = resolved- // This event is intentionally local: Desktop preferences do not belong+ // These events are intentionally local: Desktop preferences do not belong// to the System transport or to any other Desktop representation.- await this.tunnel.publish("change", preferences)+ if (changed) await this.tunnel.publish("change", preferences)+ if (changedResolved) await this.tunnel.publish("changeResolved", resolved)}}-function samePreferences(first: DesktopPreferences, second: DesktopPreferences) {+function samePreferences<Preferences extends DesktopPreferences | ResolvedDesktopPreferences>(first: Preferences, second: Preferences) {return first.theme === second.theme&& first.animations === second.animationsdiff --git a/source/client/core/link-manager/link-manager.ts b/source/client/core/link-manager/link-manager.tsindex 7b2135d..59a8a39 100644--- a/source/client/core/link-manager/link-manager.ts+++ b/source/client/core/link-manager/link-manager.ts@@ -2,7 +2,7 @@ import { AuthManagerSnapshot } from "@server/core/link-manager/auth-manager/authimport { LinkManagerSnapshot } from "@server/core/link-manager/link-manager"import { type AuthenticationState } from "@server/core/authentication/authentication"import { type SignUpResponse } from "@server/core/link-manager/link-manager"-import { type Appearance, type DesktopPreferences, type DesktopPreferencesUpdate } from "@phreshos/core"+import { type Appearance, type DesktopPreferences, type DesktopPreferencesUpdate, type ResolvedDesktopPreferences } from "@phreshos/core"import { Forward } from "@the-link/core/decorators"import { TheLink } from "@the-link/core"import { Property } from "@the-link/core"@@ -20,10 +20,10 @@ export default class LinkManager extends TheLink {/** Immediate unresolved System Appearance and future authoritative updates. */public readonly appearance: Property<Appearance>- /** Complete effective local Desktop preferences and future updates. */+ /** What this Desktop's owner chose, what it resolves to, and their future changes. */public readonly desktopPreferences: DesktopPreferencesState- public constructor(application: Application, sourceLink: TheLink, payload: LinkManagerSnapshot, desktopPreferences: DesktopPreferences) {+ public constructor(application: Application, sourceLink: TheLink, payload: LinkManagerSnapshot, desktopPreferences: DesktopPreferences, resolvedDesktopPreferences: ResolvedDesktopPreferences) {super()@@ -35,15 +35,15 @@ export default class LinkManager extends TheLink {this.appearance = Property.consumer(this, payload.appearance.key, payload.appearance.value)- this.desktopPreferences = new DesktopPreferencesState(desktopPreferences)+ this.desktopPreferences = new DesktopPreferencesState(desktopPreferences, resolvedDesktopPreferences)}public requestDesktopPreferences(preferences: DesktopPreferencesUpdate) {return this.$inbound.publish("/change-desktop-preferences", preferences)}- public updateDesktopPreferences(preferences: DesktopPreferences) {- return this.desktopPreferences.update(preferences)+ public updateDesktopPreferences(preferences: DesktopPreferences, resolved: ResolvedDesktopPreferences) {+ return this.desktopPreferences.update(preferences, resolved)}@Forward("outbound")diff --git a/source/client/view/appearance/appearance.tsx b/source/client/view/appearance/appearance.tsxindex 1fa25fa..8877b8f 100644--- a/source/client/view/appearance/appearance.tsx+++ b/source/client/view/appearance/appearance.tsx@@ -19,14 +19,14 @@ export default function ({ children }: PropsWithChildren) {}function AppearanceRoot({ children }: PropsWithChildren) {- const { preferences } = useDesktopPreferences()+ const { resolved } = useDesktopPreferences()const [appearance, setAppearance] = useState(() => resolveStoredAppearance(localStorage.getItem(appearanceKey)))const [overlays, setOverlays] = useState<HTMLDivElement | null>(null)const remember = useCallback(function (value: Appearance) {setAppearance(value)localStorage.setItem(appearanceKey, JSON.stringify(value))}, [])- const background = appearance.colors[preferences.theme].background+ const background = appearance.colors[resolved.theme].background// A theme turns the whole screen: it fades five times as long as a change in place, softly at// both ends, so the eye follows it instead of being struck by it.@@ -36,17 +36,17 @@ function AppearanceRoot({ children }: PropsWithChildren) {return <RememberAppearanceContext.Provider value={remember}>- <UIProvider appearance={appearance} preferences={preferences}>+ <UIProvider appearance={appearance} preferences={resolved}>- <DesktopScaleProvider scale={preferences.scale} container={overlays}>+ <DesktopScaleProvider scale={resolved.scale} container={overlays}><div className="relative isolate h-dvh overflow-hidden" style={{ backgroundColor: background }}>- <ReducedMotion reduced={!preferences.animations}>+ <ReducedMotion reduced={!resolved.animations}><divclassName="absolute top-0 left-0 isolate grid font-roboto"- style={{ width: "100%", height: "100%", zoom: preferences.scale }}+ style={{ width: "100%", height: "100%", zoom: resolved.scale }}>{children}diff --git a/source/client/view/appearance/desktop-preferences.tsx b/source/client/view/appearance/desktop-preferences.tsxindex 5bc4a7c..f538e10 100644--- a/source/client/view/appearance/desktop-preferences.tsx+++ b/source/client/view/appearance/desktop-preferences.tsx@@ -5,6 +5,7 @@ import {type Transaction,type DesktopPreferences,type DesktopPreferencesUpdate,+ type ResolvedDesktopPreferences,type Theme} from "@phreshos/core"import { timing } from "@phreshos/react-ui"@@ -19,31 +20,34 @@ const scaleKey = "desktop-preferences:scale"const DesktopPreferencesContext = createContext<DesktopPreferencesOwner | null>(null)-/** Owns this browser Desktop's persisted choices and native defaults. */+/** Owns this browser Desktop's persisted choices, and what they resolve to with its browser. */export default function DesktopPreferencesProvider({ children }: Readonly<{ children: ReactNode }>) {const storedTheme = useStorage(themeKey)const storedAnimations = useStorage(animationsKey)const storedScale = useStorage(scaleKey)const nativeDark = useMediaPreference(themeQuery)const nativeReducedMotion = useMediaPreference(reducedMotionQuery)- const desiredTheme = selectedTheme(storedTheme.value, nativeDark)- const desiredAnimations = selectedAnimations(storedAnimations.value, nativeReducedMotion)- const desiredScale = resolveStoredDesktopScale(storedScale.value)- const desired = useMemo<DesktopPreferences>(() => ({ theme: desiredTheme, animations: desiredAnimations, scale: desiredScale }), [desiredAnimations, desiredScale, desiredTheme])- const [preferences, setPreferences] = useState(desired)- const current = useRef(preferences)+ const chosenTheme = chosenThemeOf(storedTheme.value)+ const chosenAnimations = chosenAnimationsOf(storedAnimations.value)+ const scale = resolveStoredDesktopScale(storedScale.value)+ const preferences = useMemo<DesktopPreferences>(() => ({ theme: chosenTheme, animations: chosenAnimations, scale }), [chosenAnimations, chosenTheme, scale])+ const desiredTheme: Theme = chosenTheme === "browser" ? nativeDark ? "dark" : "light" : chosenTheme+ const desiredAnimations = chosenAnimations === "browser" ? !nativeReducedMotion : chosenAnimations+ const desired = useMemo<ResolvedDesktopPreferences>(() => ({ theme: desiredTheme, animations: desiredAnimations, scale }), [desiredAnimations, scale, desiredTheme])+ const [resolved, setResolved] = useState(desired)+ const current = useRef(resolved)const pending = useRef<PendingCommit | null>(null)const revision = useRef(0)const transaction = useRef<Transaction>(timing("change"))const update = useCallback(function (change: DesktopPreferencesUpdate) {if (change.theme !== undefined) {- if (change.theme === "desktop") storedTheme.remove()+ if (change.theme === "browser") storedTheme.remove()else storedTheme.update(change.theme)}if (change.animations !== undefined) {- if (change.animations === "desktop") storedAnimations.remove()+ if (change.animations === "browser") storedAnimations.remove()else storedAnimations.update(change.animations ? "enabled" : "disabled")}@@ -64,7 +68,7 @@ export default function DesktopPreferencesProvider({ children }: Readonly<{ chilconst themeChanged = current.current.theme !== desired.themeif (!themeChanged) {- setPreferences(desired)+ setResolved(desired)return}@@ -72,8 +76,8 @@ export default function DesktopPreferencesProvider({ children }: Readonly<{ chilif (revision.current !== change) returnawait new Promise<void>(resolve => {- pending.current = { preferences: desired, resolve }- setPreferences(desired)+ pending.current = { resolved: desired, resolve }+ setResolved(desired)})})}, [desired])@@ -82,30 +86,30 @@ export default function DesktopPreferencesProvider({ children }: Readonly<{ chilconst root = document.documentElementconst previous = root.style.colorScheme- current.current = preferences- root.style.colorScheme = preferences.theme+ current.current = resolved+ root.style.colorScheme = resolved.themeconst commit = pending.current- if (commit && samePreferences(commit.preferences, preferences)) {+ if (commit && samePreferences(commit.resolved, resolved)) {pending.current = nullqueueMicrotask(commit.resolve)}return () => { root.style.colorScheme = previous }- }, [preferences])+ }, [resolved])useEffect(() => () => {pending.current?.resolve()pending.current = null}, [])- const owner = useMemo(() => ({ preferences, update, setTransaction }), [preferences, update, setTransaction])+ const owner = useMemo(() => ({ preferences, resolved, update, setTransaction }), [preferences, resolved, update, setTransaction])return <DesktopPreferencesContext.Provider value={owner}>{children}</DesktopPreferencesContext.Provider>}-/** Reads the complete effective state and its View-owned update operation. */+/** Reads what was chosen, what it resolves to, and the View-owned update operation. */export function useDesktopPreferences() {const owner = useContext(DesktopPreferencesContext)if (!owner) throw new Error("useDesktopPreferences() requires DesktopPreferencesProvider")@@ -121,17 +125,18 @@ export function useDesktopThemeTransaction(transaction: Transaction) {}, [owner, transaction])}-function selectedTheme(value: string | null, nativeDark: boolean): Theme {- return value === "light" || value === "dark" ? value : nativeDark ? "dark" : "light"+// Following the browser is kept as no stored value at all.+function chosenThemeOf(value: string | null): DesktopPreferences["theme"] {+ return value === "light" || value === "dark" ? value : "browser"}-function selectedAnimations(value: string | null, nativeReducedMotion: boolean) {+function chosenAnimationsOf(value: string | null): DesktopPreferences["animations"] {if (value === "enabled") return trueif (value === "disabled") return false- return !nativeReducedMotion+ return "browser"}-/** Resolves the effective scale from this Desktop's persisted representation. */+/** Reads the scale from this Desktop's persisted representation. */export function resolveStoredDesktopScale(value: string | null) {const scale = Number(value)const { minimum, maximum } = desktopPreferencesLimits.scale@@ -152,15 +157,16 @@ function useMediaPreference(query: string) {interface DesktopPreferencesOwner {readonly preferences: DesktopPreferences+ readonly resolved: ResolvedDesktopPreferencesreadonly update: (change: DesktopPreferencesUpdate) => voidreadonly setTransaction: (transaction: Transaction) => void}interface PendingCommit {- readonly preferences: DesktopPreferences+ readonly resolved: ResolvedDesktopPreferencesreadonly resolve: () => void}-function samePreferences(first: DesktopPreferences, second: DesktopPreferences) {+function samePreferences(first: ResolvedDesktopPreferences, second: ResolvedDesktopPreferences) {return first.theme === second.theme && first.animations === second.animations && first.scale === second.scale}diff --git a/source/client/view/components/desktop-host/client-process-boundary.ts b/source/client/view/components/desktop-host/client-process-boundary.tsindex 8714ef8..b0c847d 100644--- a/source/client/view/components/desktop-host/client-process-boundary.ts+++ b/source/client/view/components/desktop-host/client-process-boundary.ts@@ -541,10 +541,16 @@ export default class ClientProcessBoundary extends TheLink {this.desktopPreferencesSubscriptions.add(subscription)- if (!this.stopDesktopPreferences) this.stopDesktopPreferences = this.authManager.linkManager.desktopPreferences.tunnel.subscribe("change", (preferences: unknown) => {+ if (!this.stopDesktopPreferences) {- this.deliver("host-desktop-preferences", "change", preferences).catch(() => undefined)- })+ const tunnel = this.authManager.linkManager.desktopPreferences.tunnel+ const stops = (["change", "changeResolved"] as const).map(event => tunnel.subscribe(event, (value: unknown) => {++ this.deliver("host-desktop-preferences", event, value).catch(() => undefined)+ }))++ this.stopDesktopPreferences = () => stops.forEach(stop => stop())+ }}@@ -1308,7 +1314,7 @@ type SystemSubscriptionTarget =function desktopPreferencesSubscription(subscription: EndpointSubscription) {- return subscription.kind === "publish" && subscription.route === "host-desktop-preferences" && (subscription.event === null || subscription.event === "change")+ return subscription.kind === "publish" && subscription.route === "host-desktop-preferences" && (subscription.event === null || subscription.event === "change" || subscription.event === "changeResolved")}function appearanceSubscription(subscription: EndpointSubscription) {diff --git a/source/client/view/components/desktop-host/host.ts b/source/client/view/components/desktop-host/host.tsindex 20adc4a..896b220 100644--- a/source/client/view/components/desktop-host/host.ts+++ b/source/client/view/components/desktop-host/host.ts@@ -344,7 +344,9 @@ export default function host(authManager: AuthManager, pane: string, viewport: Dreturn []}- if (word === "desktopPreferences") return [authManager.linkManager.desktopPreferences.value]+ if (word === "desktopPreferences") return [authManager.linkManager.desktopPreferences.preferences]++ if (word === "resolvedDesktopPreferences") return [authManager.linkManager.desktopPreferences.resolved]if (word === "updateDesktopPreferences") {diff --git a/source/client/view/structure/structure.tsx b/source/client/view/structure/structure.tsxindex a9788e3..1db612b 100644--- a/source/client/view/structure/structure.tsx+++ b/source/client/view/structure/structure.tsx@@ -80,7 +80,7 @@ function DesktopReadiness({ appearance }: { appearance: ReturnType<typeof useAppfunction Desktop() {const application = ApplicationContext.useValue()- const { preferences } = useDesktopPreferences()+ const { preferences, resolved } = useDesktopPreferences()const [linkManager, setLinkManager] = useState<LinkManager | null>(null)@@ -90,7 +90,7 @@ function Desktop() {return application.httpClient.onSubscribe<LinkManagerSnapshot>(function (link) {- const manager = new LinkManager(application, link, link.payload, preferences)+ const manager = new LinkManager(application, link, link.payload, preferences, resolved)link.$internal.subscribeOnce("unsubscribe", () => {setLinkManager(current => current === manager ? null : current)@@ -98,7 +98,7 @@ function Desktop() {setLinkManager(manager)})- }, [application, preferences])+ }, [application, preferences, resolved])useEffect(subscribe, [subscribe])@@ -138,7 +138,7 @@ function ConnectedDesktop({ linkManager }: { linkManager: LinkManager }) {useReady(connectionRequirement)- const { preferences, update } = useDesktopPreferences()+ const { preferences, resolved, update } = useDesktopPreferences()const inbound = ReactTunnel.useFactory(linkManager.$inbound)@@ -151,8 +151,8 @@ function ConnectedDesktop({ linkManager }: { linkManager: LinkManager }) {useRememberSystemAppearance(appearance)useEffect(function () {- void linkManager.updateDesktopPreferences(preferences)- }, [linkManager, preferences])+ void linkManager.updateDesktopPreferences(preferences, resolved)+ }, [linkManager, preferences, resolved])return <LinkManagerContext.Provider value={linkManager}>diff --git a/tests/link-request-routing.test.ts b/tests/link-request-routing.test.tsindex 513504a..63e70d3 100644--- a/tests/link-request-routing.test.ts+++ b/tests/link-request-routing.test.ts@@ -2,7 +2,7 @@ import assert from "node:assert/strict"import { mkdtemp, rm } from "node:fs/promises"import { tmpdir } from "node:os"import { join } from "node:path"-import { defaultAppearance, type DesktopPreferences } from "@phreshos/core"+import { defaultAppearance, type DesktopPreferences, type ResolvedDesktopPreferences } from "@phreshos/core"import { TheLink } from "@the-link/core"import ClientLinkManager from "@client/core/link-manager/link-manager"import Application from "@server/core/application"@@ -56,24 +56,32 @@ test("Desktop preferences remain inside their owning browser Desktop", async ()const source = new TheLink()const outbound: unknown[][] = []- const preferences: DesktopPreferences = { theme: "light", animations: true, scale: 1 }- const changed: DesktopPreferences[] = []+ const preferences: DesktopPreferences = { theme: "browser", animations: true, scale: 1 }+ const resolved: ResolvedDesktopPreferences = { theme: "light", animations: true, scale: 1 }+ const changed: unknown[][] = []const stopOutbound = source.$outbound.forwardTo((event, ...values) => { outbound.push([event, ...values]) })const manager = new ClientLinkManager({} as never,source,{ appearance: { key: "appearance", value: defaultAppearance } },- preferences+ preferences,+ resolved)- const stopChanged = manager.desktopPreferences.tunnel.subscribe("change", value => { changed.push(value as DesktopPreferences) })- const next: DesktopPreferences = { ...preferences, theme: "dark" }+ const stops = (["change", "changeResolved"] as const).map(event => manager.desktopPreferences.tunnel.subscribe(event, value => { changed.push([event, value]) }))+ const stopChanged = () => stops.forEach(stop => stop())+ const darkBrowser: ResolvedDesktopPreferences = { ...resolved, theme: "dark" }+ const chosenDark: DesktopPreferences = { ...preferences, theme: "dark" }try {- await manager.updateDesktopPreferences(next)- await manager.updateDesktopPreferences(next)+ // The browser turns dark while it is followed: only what is used changes.+ await manager.updateDesktopPreferences(preferences, darkBrowser)+ await manager.updateDesktopPreferences(preferences, darkBrowser)+ // The owner chooses dark, which it already resolves to: only what was chosen changes.+ await manager.updateDesktopPreferences(chosenDark, darkBrowser)- assert.deepEqual(manager.desktopPreferences.value, next)- assert.deepEqual(changed, [next])+ assert.deepEqual(manager.desktopPreferences.preferences, chosenDark)+ assert.deepEqual(manager.desktopPreferences.resolved, darkBrowser)+ assert.deepEqual(changed, [["changeResolved", darkBrowser], ["change", chosenDark]])assert.deepEqual(outbound, [])}finally {